Currently i have started learning in React to call API but when component is rendered on browser side from below code toast message is shown two times instead of single time. Can someone please help me to fix this issue? Thanks in advance!
const [toastShown, setToastShown] = useState(false);
useEffect(() => {
document.title = "All Courses";
axios.get(`${base_url}/courses`).then(
(response) => {
setCourses(response.data);
if (!toastShown) {
toast.success("Courses loaded successfully!");
setToastShown(true);
}
},
(error) => {
toast.error("Something went wrong!");
}
);
}, [toastShown]);
In the development mode,
StrictModeis enabled which runsuseEffecttwice. Try to build the code and test it inProductionmode. If it runs twice, try to useAbortControllerto stop the first API call, which stops the execution ofthen.