skip to Main Content

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

2

Answers


  1. 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();
    },  []);
    
    Login or Signup to reply.
  2. Use this when user opens the screen

    useEffect(() => {
    
        const subscribe = navigation.addListener('focus', () => {
           // your user data code
        })
    
        return () => {
            subscribe;
        }
    }, [])
    
    const navigation = useNavigation()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search