When I am canceling API calls on unmounting and again visiting the same page, the apis are not called again.
const cancelToken = axios.CancelToken;
export const signal = cancelToken.source();
I am using this in my baseconfig.js for Axios, and my component has this in the useEffect
useEffect(() => {
return () => {
props.dispatch({
type: LEAVE_PAGE,
});
console.log("Unmounting");
signal.cancel();
};
},[]);
The API is being canceled as soon as I leave the page or component is unmounted, but on visiting again the API that was canceled is not being called. I am using the same token for all the apis.
You have export const signal = cancelToken.source();
written above. This implies to me that you are creating one global signal, external to the component, but mutating it (e.g. by cancelling it) within the component.
You should instead instantiate this signal within your component and use it there. That way, you will get a new signal each time the component mounts. You can make sure to not create a new signal on every re-render by using e.g. useMemo
. Consider:
const YourComponent = (props) => {
const signal = useMemo(() => axios.CancelToken.source(), []);
useEffect(() => {
return () => {
props.dispatch({
type: LEAVE_PAGE,
});
console.log("Unmounting");
signal.cancel();
};
}, []);
...
};