-2

Currently i am passing local stored user details to hooks variable inside useEffect. i can get the data from local storage but same values are not passing to hooks variable. i want this value to be update in state when component mount. i checked using console.log and data passing to variable from localStorage

[function App() {
const [usercred , setUsercred] = useState({
  id:'',
  display : '',
  picture : '',
  token : '',
  isAuthenticated : false
});
  
  useEffect(() =>{
    const user = JSON.parse(localStorage.getItem('user'));
    setUsercred({id:user.id,
      display : user.display,
      picture: user.picture,
      token : user.token,
      isAuthenticated : true
    });
    console.log("Below data from 'user'")
    console.log(user);

    console.log("Below data from Hooks Variable")
    console.log(usercred);
  },[])   
    
Luca Rasconi
  • 1,085
  • 11
  • 30
user9518129
  • 3
  • 1
  • 2
  • 3
    Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – Zeno Dalla Valle Apr 06 '21 at 12:51
  • If you want to initialize a state of the `useState` hook you should use the initializer of that hook: `const [state, setState] = useState(() => tryReadLocalStorage('user'));` – Martin Apr 06 '21 at 13:18

1 Answers1

0

The way you check is not correct.
When you do console.log(usercred); inside useEffect function, the state variable usercred will be updated in the next render.
For example, if you put usercred in the dom

<div>{usercred.isAuthenticated}</div>

you will see it changing.

Luca Rasconi
  • 1,085
  • 11
  • 30