0

I have this weird scenario where when i relog with different account in my project it renders 3 times previous account's data and then it renders current account's data as expected. This causes some unnecessary network calls and many other bugs. I have been examining this problem and this is the only function where I set userData.
why this useEffect:

useEffect(() => {
    if (userData?.status === 500) {
      setItemToLocalStorage("token", "")
      history.push("/login")
    }

    let updatedState = {...state}
    console.log(`${updatedState?.isAdmin} before`)
    if (userData && userDataFetched) {
      updatedState = {
        ...updatedState,
        isAdmin: userData?.isQappAdmin,
        userRole: userData?.roles[0],
        userName: userData?.userName
      }
      if(userData?.roles[0] !== IRoles.WASHER_MANAGER) {
        updatedState = {
          ...updatedState,
          user: userData        
        }
      }
    }
    console.log(`${updatedState?.isAdmin} after`)
    setState(updatedState)
  }, [userData])

logs:

false before
true after
true before
false after

?

Nika
  • 107
  • 11
  • You are cloning the state outside of the condition, so the setState call will always trigger a render even if no changes are made. Move the setState call inside the condition (and the initial `let updatedState = {...state};` is redundant, just spread it once when you actually update it.) – pilchard Jun 29 '23 at 09:43
  • I have tried what you have suggested but it changed nothing :/ I moved `setState` inside if statement and also moved `let updatedState = {...state};` into if else statement. Could you please provide an exact code in case I do something wrong? – Nika Jun 29 '23 at 10:01
  • Is `userData` saved in state or just `const userData = { someKey: 123 };`? Because React struggles with "complex" obects in `useEffect` dependency arrays (see: https://stackoverflow.com/questions/54095994/react-useeffect-comparing-objects) – Harrison Jun 29 '23 at 10:15
  • You'll need to show what else is happening to update `userData` for concrete help – pilchard Jun 29 '23 at 10:22
  • `IUser { userId: string userName: string isQappAdmin: true, roles?: IRoles }` this is the type of `userData`. userData is an object, which is saved in state. I am using useContext. – Nika Jun 29 '23 at 10:24

0 Answers0