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])