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]);
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.
state updates in react are asynchronous so if you are setting state multiple times at different places in code. then directly using the ...state variable to get the previous value might not work as expected.
Instead of setting a state like this -
setState({ ...state, pageCount: res.data.pageCount })
Try out this to get the previous value from the state -
setState((prevState) => ({ ...prevState, pageCount: res.data.pageCount }))
And you need not add state.labs in dependency array, it will going to cause infinite loop if you are changing value of dependency array inside same useEffect.