취업/React.JS

[React] react-toastify 중복호출 막기.

카슈밀 2024. 3. 14. 11:58
반응형

리액트 토스티파이 사용중인데, 중복 호출이 되는 문제가 발생했다.

이를 어떻게 막나 고민했는데, 방법이 쉽게 나오나했다.

https://fkhadra.github.io/react-toastify/introduction/

 

React-toastify | React-Toastify

Financial Contributors on Open Collective

fkhadra.github.io

<ToastContainer
    position="top-right"
    autoClose={1000}
    limit={1}
/>

 

바로 container에서 limit 1을 넣는 것.

그런데, 이건 그냥 알림을 1개로 제한하는 기능이라.

연속호출시 꺼지면 다시 여러번 호출되는 문제가 발생하더라.

 

 

그래서 찾아보니

https://fkhadra.github.io/react-toastify/prevent-duplicate/

 

Prevent duplicate | React-Toastify

There are two ways to prevent duplicates toast. Use the one that fits your use case 👌.

fkhadra.github.io

요런 문서가 나오더라.

 

ref를 사용해서 하는 방식과 custom Id를 만들어서 사용하는 방법 중

내게 맞는 방법은 ref가 아닌 custom id를 만들어서 사용하는 방식이었다.

ref의 경우 나는 따로 호출용 함수.js로 빼놨는데, 그 경우 처리가 불가능했다.

dom에러 발생.

 

그래서 함수 호출할때, 

import React from 'react';
import { toast } from 'react-toastify';

const customId = "custom-id-yes";

function Example(){
  const notify = (text) => {
    toast(text, {
      toastId: text
    });
  }
notify(123);

  return (
    <div>
      <button onClick={notify}>Notify</button>
    </div>
  )
}

 

문제가 되는 경우가

text가 같은 경우일테니 text를 toastId로 해두니 동일한 내용시 중복 호출이 아예 막혔다.

만세!

728x90