I'm using React Context and a reducer for state management, and I would like my app to check whether a given state is empty when the user logs in - if yes, then it should fill the state with a value, and if no (so if the value has already a string value), then it should empty it out with an empty string. The problem is that it runs on an infinite loop and I can't figure out how to get out of it!
useEffect(() => {
if (userData.name === '' && isAuthenticated) {
setUserData({ ...userAuth0 });
} else if (userData.name !== '' && !isAuthenticated) {
setUserData({
nickname: '',
name: '',
picture: '',
email: '',
emailVerified: false
});
}
}, [isAuthenticated]);
I get the following error on the console:
Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.
Ideally this code would only be ran when the isAuthenticated state from Auth0 changes in the app. It however runs all the time, non-stop. The idea is that when the user is authenticated AND the current state is an empty string, then it would fill the state in. Then when the user is NOT authenticated anymore and there's a value still stored in the state, then I want it to be emptied out.
Here is the codesandbox: https://codesandbox.io/s/hardcore-euclid-78ggk0?file=/src/App.tsx
Thank you!
Tried the code in an out the useEffect and I keep getting the same infinite loop.