Search code examples
react-nativereact-reduxreact-hooksuse-effectdispatch

UseEffect reads value correctly but value is undefined if accessed elsewhere


I currently have the following code in my react-native project:

const currUser = useSelector((state) => state.userState);
  const {currentUser, listings} = currUser;

  const dispatch = useDispatch();

  useEffect(() => {
    if (!currentUser) {
      dispatch(fetchUser());
    } else {
      console.log('This is the current user');
      console.log(currentUser);
    }
    dispatch(fetchUserListings());
  });

And later on in the same function have the following line of code:

<Text style={[styles.username, {width: '50%'}]}>
            @{currentUser.username}
</Text>

When I run my app, I get an error saying "currentUser.username" is invalid because undefined is not an object, however my console prints the following output:

This is the current user
Object {
  "email": "[email protected]",
  "username": "test13",
}

which means that the code inside the useEffect is getting executed and currentUser is populated. I'm really confused as to why I am able to access the value of currentUser inside the useEffect, however am not able to do the same outside the useEffect.


Solution

  • what is happening is actually the value of currentUser is undefined the first time until the API call executes and the value gets set. The value you logging in useEffect is after getting the value but the error is happening before that.

    so if you just let's say do this (just assign an empty object if undefined):

    const {currentUser = {}, listings} = currUser;
    

    it will not give you the error.