I am developing an eComm site where I persist the user's cart to global state and to the browser's local storage.
When they head to the Cart or Checkout page, I take the global state and send it to an API for verification and get back the "true" state of the cart. I then want to update the global state to reflect this API data.
So the App mounts, checks for local storage and creates the global state from this. On the Cart and Checkout pages, I have a useEffect listening to a global useContext for global state changes.
I cant use on mount as the local storage hasn't loaded by this stage
useEffect(()=>{}, [])
How can I avoid the loop this creates?
Here is the gist of the useEffect and dependency.
TIA!
const globalState = useGlobalState()
const dispatch = useDispatchGlobalState()
useEffect(() => {
if (globalState.cart.length > 0) {
fetch('/api...', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(globalState.cart)
})
.then((response) => {
return response.json()
})
.then((dbcart) => {
dispatch({
type: 'update global state',
payload: {
cart: dbcart
}
})
})
.catch((error) => {
...
})
}
}, [globalState])
Your globalState is an object. Upon updating that object via dispatch changes the references to that object. Since your object is in the dependency array of your useEffect. useEffect runs again causing a triggering multiplie re-renders.
Make sure to use a variable as a dependency in your
useEffect
.Also, you could use a ref and updated the ref when the dispatch is done. Upon next re-render, you could check for the ref.