I am using React JS, Redux, React- Redux , Redux-Thunk.
File: Acions.js: Here are my Redux Action functions:
export function setSuccess(data){
return{
type: "SET_SUCCESS",
payload: data
};
}
export function setMessage(data){
return{
type: "SET_POSTS",
payload: data
};
}
export const listMyBlogPosts = (userID, abortController) =>{
return (dispatch) =>{
axios.get(`http://locahost:5000/timeline/posts/${userID}`, {signal: abortController})
.then((response) =>{
dispatch(setSuccess(true));
dispatch(setMessage(response.data.message));
}).catch((error) =>{
console.log("err: ", error);
dispatch(setSuccess(false));
dispatch(setMessage(`${error}`));
});
}
};
Here is where I am using the above function:
File: ABC.js:
function ABC({ someCheck }){
const abortController = useRef(new AbortController());
const dispatch = useDispatch();
console.log(“ABC component”);
useEffect(() =>{
navigation.addListener("focus", () =>{
dispatch(listMyBlogPosts(userID, abortController.current.signal));
console.log("focus is being run!");
});
return () => abortController.current.abort();
}, []);
}
In the ABC component, I get the following error:
If I remove the useEffect hook, I do not get the above error ?
How to fix this error ?
Your code is adding more and more event 'focus' listeners, which is leading to lots of request call. So you need to remove those event listener once component is unmounted.
useEffect(() => {
const onFocus = () => {
dispatch(listMyBlogPosts(userID, abortController.current.signal))
console.log('focus is being run!')
}
navigation.addListener('focus', onFocus)
return () => {
navigation.removeListener('focus', onFocus)
abortController.current.abort()
}
}, [])