본문 바로가기

TIL

TIL 23.01.18 react-toastify 중복 처리

기존에 있는 alert 창은 디자인이 마음에 안들어서 toastify 라이브러리를 이용하기로 했다.

 

참고문서 

 

https://fkhadra.github.io/react-toastify/limit-the-number-of-toast-displayed/

 

Limit the number of toast displayed | React-Toastify

Notifications are useful to get the attention of the user. But displaying too many of them can also be counterproductive.

fkhadra.github.io

 

react-toastify 설치 명령어

$ npm install --save react-toastify
$ yarn add react-toastify

 

다음처럼 명령어를 객체로 묶어서 하나로 정리해주었다.

export const TOAST_TEXT = {
  // login
  LOGIN_WARN: "로그인이 필요한 작업입니다.",
  LOGOUT_SUCCESS: "로그아웃 되었습니다.",
  LOGIN_SESSION_ERROR: "세션이 만료되었거나 비정상적인 접근입니다.",
  LOGIN_EXPIRED_ERROR: "로그인 정보가 만료되었습니다. 다시 로그인 해주세요.",
  LOGIN_UNDEFINED_ERROR: "알 수 없는 오류입니다. ",
};

 

이후, Toast 기능별로 (success, warn, error, info) 나누었다.

export const ToastSuccess = (text: string) => {
  toast.success(`${text}`, {
    position: "top-center",
    autoClose: 700,
    pauseOnHover: false,
  });
  return;
};

 

 

문제점 1

 

여기서 문제는, toastify 알람을 반복실행하게 되면 창이 한번에 여러개가 뜨게된다.

 

해결방안

 

이는 ToastContainer 에 있는 limit 을 이용하여 갯수를 설정해줄 수 있다. 그러면 여러번 누르면 차례대로 하나씩만 나오게 된다.

  <ToastContainer limit={1} transition={Bounce} />

 

 

문제점 2

 

근데 여기서 또 문제가 생기는게, 하나씩만 나오다보니 네번연속으로 눌렀다고 가정하면 토스트창이 하나씩 네번 연속으로 나오는 일이 생김.

 

해결방안

 

이를 해결하기 위해, 다음 속성을 넣어주었다. 이는 표시되는 토스트 수의 제한을 위한 것으로, 대기열을 지우는 method.

  toast.clearWaitingQueue();

 

 

적용하고 나니, 버튼을 반복해서 눌러도 토스트창이 활성화 되었으면 하나씩만 나온다. 🤭