[Ngether] Alert 띄우기

hzn·2023년 3월 15일
0

PROJECT🏝

목록 보기
10/24
post-thumbnail

SNS 공유 : URL 복사

다른 버튼은 클릭 시 해당 SNS 공유 팝업이 새로 뜨지만 URL copy 버튼은 주소 복사가 성공했을 시 아무런 표시가 없어 성공 시 팝업 alert을 띄워주기로 했다.

Share.tsx

import React, { useState } from 'react';
import { Alert, AlertColor, Snackbar } from '@mui/material';

const [open, setOpen] = useState(false);

const handleCopyAlert = () => {
    setOpen(true);
  };

const handleClose = (
    event?: React.SyntheticEvent | Event,
    reason?: string
  ) => {
    if (reason === 'clickaway') {
      return;
    }
    setOpen(false);
  };

   return (
     ...
      <CopyToClipboard text={currentUrl}>
            <button
              onClick={handleCopyAlert}
              className="flex justify-center items-center w-12 h-12 rounded-full text-lg text-white bg-[#f48b3a] hover:bg-[#adaba9]"

              URL
            </button>
          </CopyToClipboard>
...
 	   <Snackbar
          open={open} // 초기값은 false
          autoHideDuration={2000} // alert 떠 있는 시간
          onClose={handleClose}
          className="bottom-[25%]"
          anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}

          <Alert severity="success">URL이 복사되었습니다!</Alert>
        </Snackbar>
      </Box>
    </div>
  );
};

게시물 수정 완료 시

  • 경우에 따라 alert 여러 개일 경우 (성공 시, 에러 시...)

pages > edit > [id].tsx

import { useState } from 'react';
import { Alert, AlertColor, Box, Snackbar } from '@mui/material';

  const [open, setOpen] = useState(false);

// alertOption State와 초기값 지정
  const [alertOption, setAlertOption] = useState<{
    severity: AlertColor;
    value: string;
  }>({ severity: 'error', value: '' });

const { isLoading, error, mutate } = useMutation(
    () => editProductDetail(id, requestBody),
    {
      onSuccess: async (data) => { // 요청 성공 시 
        setOpen(true); // alert 띄우기
        setAlertOption({ // 성공 시 옵션
          severity: 'success',
          value: '게시글이 수정되었습니다',
        });
        router.push(`/nearby/${id}`);
      },

      onError: (error) => { 
        setOpen(true); // alert 띄우기
        setAlertOption({ // 에러 시 옵션
          severity: 'error',
          value: '게시물 수정에 실패했습니다. 잠시 후 다시 시도해주세요',
        });
      },
    }
  );

 const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    const validation = validatePostInput({ // 유효성 검사
      title,
      address: targetCoord?.address,
      productsLink: encodeURIComponent(productsLink),
      maxNum,
      deadLine,
      content,
      setOpen,
      setAlertOption,
    });
    if (!validation) return;

    mutate(); // 쉐어링 수정 버튼 클릭 시 mutate() 실행
  };

  const handleClose = (
    event?: React.SyntheticEvent | Event,
    reason?: string
  ) => {
    if (reason === 'clickaway') {
      return;
    }
    setOpen(false);
  };
...
return (
 <Box component="form" onSubmit={handleSubmit}> // 버튼 클릭 시 onSubmit
...
 	<FormButton
        className="h-14 mt-4"
        variant="contained"
        content="쉐어링 수정"
        type="submit"
     />
  </Stack>
 </FormControl>
 <Snackbar
     open={open}
     autoHideDuration={4000}
     onClose={handleClose}
     className="bottom-[25%]"
     anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}

      <Alert severity={alertOption?.severity}>{alertOption?.value}</Alert> // 옵션에 따라 다른 alert
  </Snackbar>
  </div>
</Box>

0개의 댓글