Search code examples
reactjsreact-nativees6-promiseasyncstorage

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


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?


Solution

  • 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;
        }
    };