0

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.

Irina
  • 59
  • 7
  • 1
    You have not posted enough code to answer the question. Post at least the rest of the component that defines and manipulates `isAuthenticated` – possum Nov 06 '22 at 19:15
  • @possum `isAuthenticated` comes from Auth0, it's basically just: `import { useAuth0 } from '@auth0/auth0-react';` and then `const { userAuth0, isAuthenticated } = useAuth0();` – Irina Nov 06 '22 at 20:40

1 Answers1

1

You are duplicating the state of userAuth0 to the state of your component. This is redundant, just use the userAuth0, you don't need to setUserData at all.

Also, your link to sandbox doesn't work as it is not public:(

Marat
  • 618
  • 1
  • 6
  • 10
  • The code in sandbox is different from the question and works fine. Have you tried to do what I suggested in the answer? (removing userData from state, removing useEffect and just using the data provided by auth0 in your component) – Marat Nov 07 '22 at 09:51
  • Indeed my apologies, here is the good link now https://codesandbox.io/s/hardcore-euclid-78ggk0?file=/src/App.tsx – Irina Nov 07 '22 at 11:58
  • 1
    Your idea of erasing this userData altogether actually makes more sense though, if I directly fetch the data from Auth0 is a lot more practical – Irina Nov 07 '22 at 11:59