Search code examples
reactjsreact-nativereact-hooksasyncstorage

react native asyncStorage with useEffect rendering


I'm trying to get item from local storage but its not rendering with me correctly, which I should refresh the app by making any change in the code and save whenever I log in or logout here is my code

enter image description here

    useEffect(() => {
    const _getUserhData = async () => {
        try {
            let userInfo = await AsyncStorage.getItem('userData');
            if (userInfo) {
                const parsedUserData = JSON.parse(userInfo);
                setUserData(parsedUserData);
                console.log(userData, 'userData');

            }
        } catch (error) {
            console.error('Error retrieving data:', error);
        }
    };

    _getUserhData();
},  [userInfo]);

Solution

  • From what you have shared there is no userInfo declared in scope, e.g. the scope of the React function component body.

    From what I can tell of your code you should just remove userInfo and use an empty dependency array since there are no external dependencies in the useEffect hook callback.

    const [userData, setUserData] = React.useState(null);
    
    useEffect(() => {
      const getUserData = async () => {
        try {
          const userInfo = await AsyncStorage.getItem('userData');
          setUserData(JSON.parse(userInfo));
        } catch (error) {
          console.error('Error retrieving data:', error);
        }
      };
    
      getUserData();
    },  []);