React-Native Async Storage returns weird object with correct value in two consecutive lines

740 Views Asked by At

I've researched this and not found a similar case answered, at my whits end.

I have the following code to get an item from AsyncStorage, which returns the correct value when I log it on the console, but the function's return value is: {\"_40\":0,\"_65\":1,\"_55\":\"Nick\",\"_72\":null}

const getData = async () => {
    try {
        const value = await AsyncStorage.getItem('userDetails');
        if(value !== null) {
            const wsi_user = await JSON.parse(value);
            console.log("userName: " + wsi_user.userName); // returns "Nick"
            return wsi_user.userName; // returns {\"_40\":0,\"_65\":1,\"_55\":\"Nick\",\"_72\":null}
        }
    } catch(e) {
        letter = "D";
    }
}

I've seen similar articles where people mention that the promise needs to resolve and I get that, but my result is within the outputted weird object, AND, my result is correct when logged to console the line before return.

Please advise. No clue how to fix this.

3

There are 3 best solutions below

1
On

You can call this function like:

const result = await getData()

Also, you don't need the await before JSON.parse() as it is synchronous.

1
On

You need to convert the object to a string before saving it in the async storage AsyncStorage.setItem(key, JSON.stringify(data));

Example:

export const setStorageItem = async (key: string, data: any): Promise<void> => {
  return AsyncStorage.setItem(key, JSON.stringify(data));
};

export const getStorageItem = async <T>(key: string): Promise<T | null> => {
  const item = await AsyncStorage.getItem(key);
  if (item) {
    return JSON.parse(item);
  }
  return null;
};

Example from the docs

0
On

Maybe you can use react-native-easy-app, through which you can access AsyncStorage synchronously, and can also store and retrieve objects, strings or Boolean data

  import { XStorage } from 'react-native-easy-app';
  import { AsyncStorage } from 'react-native';
  // or import AsyncStorage from '@react-native-community/async-storage';

   export const RNStorage = { userInfo: undefined  };
   
  const initCallback = () => {

       // From now on, you can write or read the variables in RNStorage synchronously
       
       // equal to [ await AsyncStorage.setItem('userInfo',JSON.stringify({ name:'rufeng', age:30})) ]
       RNStorage.userInfo = {name: 'rufeng', age: 30}; 
  };
  
  XStorage.initStorage(RNStorage, AsyncStorage, initCallback);