Why am i getting an undefined output when I try to access value returned from async method

139 Views Asked by At

I have the following method which returns an object with 3 fields inside a different file named localStorage:

    const getUserProfileData = async () => {
    try {
        await AsyncStorage.getItem(CONSTANTS.USER_PROFILE).then((item) => {
        let retrievedProfile = JSON.parse(item);
        return retrievedProfile;
        });
    } catch (e) {
        throw e;
    }
    };

here is my file profile.js:

  useEffect(() => {
    const retrieveProfileData = async () => {
      let retProfile = await localStorage.getUserProfileData();
      console.log("check what:  ",retProfile);
    };
    retrieveProfileData();
  }, []);

inside the use effect, when I attempt to log out the result I get an output of:

check what:   undefined

I have read other forums on similar problems to this but I can't seem to notice where I'm going wrong?

2

There are 2 best solutions below

0
On BEST ANSWER

I think it has to do with you mixing async and .then(). Try this way:

const getUserProfileData = async () => {
    try {
        const result = await AsyncStorage.getItem(CONSTANTS.USER_PROFILE)
        const retrievedProfile = JSON.parse(result);
        return retrievedProfile;
    } catch (e) {
        throw e;
    }
};
0
On
    const getUserProfileData = async () => {
        return AsyncStorage.getItem(CONSTANTS.USER_PROFILE);
    };

    useEffect(() => {
    const retrieveProfileData = async () => {
        try {
        let retProfile = JSON.parse(await localStorage.getUserProfileData());
        console.log("check what:  ",retProfile);
        } catch (error) {
            // handle error
        }
    };
    retrieveProfileData();
    }, []);