I'm using redux and trying to fetch data when my component did update. I'm using useEffect hook to track posts update and getting the state with useSelector. I'm having issues as the component is making infinite fetching requests instead of a single request. Anyone knows how I can stop it from making infinite requests and make a single request if posts updated?
my code:
const posts = useSelector((state) => state.posts.posts);
useEffect(() => {
dispatch(getPosts(page));
}, [posts]);
const posts = useSelector((state) => state.posts.posts);
useEffect(() => {
dispatch(getPosts(page));
}, []);
const updateNeeded = useSelector((state) => state.posts.updateNeeded);
useEffect(() => {
if (updateNeeded) {
dispatch(getPosts(page));
}
}, [updateNeeded]);
Change updateNeeded to true by a dispatch action when you want to fetch a new update, and when the update is fetched dispatch an action which will make this flag to false again.
From useEffect
documentation
If you're familiar with React class lifecycle methods, you can think of useEffect Hook as
componentDidMount
,componentDidUpdate
, andcomponentWillUnmount
combined.
So, dispatch(getPosts(page))
will be called on component mount as well when any of the dependency provided get changed, this will make an API request and fetch the posts of this page
. Which will eventually update the state.posts.posts
once the API is successful. As, the same state.posts.posts
is given as dependency to the useEffect
hook this will trigger the function to get executed again and the cycle goes on.
For example if you want to make the API call and fetch new posts when there's a change in the page
you should provide page
as dependency instead of posts
as shown below
const posts = useSelector((state) => state.posts.posts);
useEffect(() => {
dispatch(getPosts(page));
}, [page]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.