When I use this the labs field only gets updated for a millisecond and is gone after that.
// the pagination component
const [state, setState] = useState({
pageCount: 0,
currentPage: 0,
labs: [],
});
useEffect(() => {
labPageCount()
.then((res) => setState({ ...state, pageCount: res.data.pageCount }))
.catch(console.log);
}, [state.pageCount]);
useEffect(() => {
fetchLabs(state.currentPage)
.then((res) => setState({ ...state, labs: res.data }))
.catch(console.log);
}, [state.currentPage]);
Now if I add labs to the array in the second useEffect(), then it results in an infinite loop:-
useEffect(() => {
fetchLabs(state.currentPage)
.then((res) => setState({ ...state, labs: res.data }))
.catch(console.log);
}, [state.currentPage, state.labs]);
CodePudding user response:
Inside the second snipped, you are changing the labs by calling setState, then you are watching the changes on state.labs which causes the hook to be run again.
Somehow you need to compare labs then if they are different you should setState.
Alternatively you can call fetchLabs where you change the labs instead of calling in useEffect hook.
CodePudding user response:
Check this solution: enter link description here
