Search code examples
javascriptreactjsreact-hooksuse-effect

Cannot setState after receiving user from service provider


I am receiving the user properly from my provider but for some reason the state does not change with the user object.

This returns the user object properly:

console.log(receivedUser);

However, after I try to do this, there's no object:

setUser(receivedUser);
  console.log(user);

What seems to be the issue here guys? Why doesn't the state change at all?

Full code:

const [user, setUser] = useState({})

// this prevents this providerValue changing unless value or setValue changes
const providerValue = useMemo(() => ({user, setUser}), [user, setUser])

  useEffect(() => {
    async function fetchUser(){
    const receivedUser = await AuthService.getCurrentUser();
    if (receivedUser) {
      // console.log(receivedUser);
      setUser(receivedUser);
      console.log(user);
    } else {
      console.log("user not logged in");
    }
    }
    fetchUser();
  }, []);

Solution

  • updation of state is asynchronous. you need to use useEffect to console out the value of state. A seperate useEffect can be created which would be triggered every time the user in the state changes

    const [user, setUser] = useState({})
    
    // this prevents this providerValue changing unless value or setValue changes
    const providerValue = useMemo(() => ({user, setUser}), [user, setUser])
    
      useEffect(() => {
        async function fetchUser(){
        const receivedUser = await AuthService.getCurrentUser();
        if (receivedUser) {
          // console.log(receivedUser);
          setUser(receivedUser);
          console.log(user);
        } else {
          console.log("user not logged in");
        }
        }
        fetchUser();
      }, []);
    
        useEffect(()=> {
            console.log('user',user)
        }, [user])