I am working in React with Redux. I have written the action called products to fetch the product details from backend using Axios. In that, I used cancel token to cancel the HTTP request if the user navigates to another page during the process.
But still, I got the error in the console like below when I navigate to another page.
index.js:1 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
When I navigate to the same product page to fetch the data, the request goes to the catch block to throw the error. I used the below code to dispatch the action.
product.js as action
const source = Axios.CancelToken.source();
const fetchProducts = () => {
return async (dispatch) => {
try {
const response = await Axios.get("myurl", {
cancelToken: source.token,
});
if (response.status !== 200) {
throw new Error("Something went wrong, while fetching the products!");
}
dispatch({ type: GET_PRODUCTS, products: response.data });
} catch (err) {
if (Axios.isCancel(err)) {
console.log(err.message);
} else {
throw err;
}
}
};
};
const cancelRequest = () => {
return (dispatch) => {
if (source !== typeof undefined) {
source.cancel("Operation canceled by the user.");
dispatch({ type: CANCEL_REQUEST, message: "Request canceled by user!" });
}
};
};
component file:
const loadProducts = useCallback(async () => {
setError(null);
try {
await dispatch(productActions.fetchProducts());
} catch (err) {
setError(err.message);
}
}, [dispatch, setError]);
useEffect(() => {
setIsLoading(true);
loadProducts().then(() => {
setIsLoading(false);
});
return () => {
dispatch(productActions.cancelRequest());
};
}, [dispatch, loadProducts, setIsLoading]);
How to resolve this issue?