삭제나 등록 등 버튼을 클릭했을때 ‘해당 ㅇㅇ이 삭제 되었습니다’ 라는 toast를 사용하기 위해 Toast컴포넌트를 만들어서 사용했었다. 그런데 보통 데이터가 성공적으로 가져왔을 경우 toast를 띄어주는데…만들어 놓은 Toast 컴포넌트를 사용하려니 로직이 굉장히 복잡해져갔다…😧
그 상황이 있었는데 현 프로젝트에서는 react-query를 사용해서 데이터를 fetch를 하고 있다. onSuccess가 콜백되었을때 직접만든 Toast 컴포넌트를 사용하려니 어떻게 사용해야할지 감이 잡히지 않았다. 오히려 억지로 Toast 컴포넌트를 사용하려니 코드가 방대해져서 복잡해지는 느낌이 들었다.
알아보니 toast 라이브러리를 사용하면 react-query의 콜백함수에서도 굉장히 간단하게 toast처리를 해줄 수 있는거 같았다.
‼️당장 설치‼️
react-toastify 선택 이유
사용법
import React from 'react';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
function App(){
const notify = () => toast("Wow so easy !");
return (
<div>
<button onClick={notify}>Notify !</button>
<ToastContainer />
</div>
);
}
export default App;
App 컴포넌트에 <ToastContainer />랑 import 만 해주면 끝.
import { toast } from 'react-toastify';
const useToast = () => {
const toastSuccess = (msg: string) => {
toast.success(msg);
};
const toastError = (msg: string) => {
toast.error(msg);
};
const toastInfo = (msg: string) => {
toast.info(msg);
};
const toastWarning = (msg: string) => {
toast.warning(msg);
};
return { toastSuccess, toastError, toastInfo, toastWarning };
};
export default useToast;
현재 프로젝트에서는 sucees,error,info,warning 4가지 정도의 toast가 필요 할 것 같아서 hook으로 빼놨다
리액트쿼리에서 사용
const usePostJoinQuery = () => {
로직 생략...
onSuccess: () => {
toastSuccess('회원가입이 완료되었습니다.');
},
onError: err => {
console.log(err);
}
});