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,
StrictMode
is enabled which runsuseEffect
twice. Try to build the code and test it inProduction
mode. If it runs twice, try to useAbortController
to stop the first API call, which stops the execution ofthen
.