react native asyncStorage with useEffect rendering

63 Views Asked by At

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]);
3

There are 3 best solutions below

4
Drew Reese On BEST ANSWER

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();
},  []);
0
Mahii On

Use this when user opens the screen

useEffect(() => {

    const subscribe = navigation.addListener('focus', () => {
       // your user data code
    })

    return () => {
        subscribe;
    }
}, [])

const navigation = useNavigation()
1
Ibrahim Khan On

useEffect(() => {
    AsyncStorage.getItem('userData').then((response) => {
        if (response) {
            const parsedUserData = JSON.parse(response);
            setUserData(parsedUserData);
            console.log(response, 'userData');

        }
    })
},  []);