Muhammad Umar
Muhammad Umar

Reputation: 319

React native async storage returning previous value

I'm using react-native-async-storage for saving API headers and user information received from API

const storeUserInfo = async (userInfo: any, headers: any) => {
  console.log(
    'Info Received in Local Storage Function',
    userInfo,
    'Headers Received in Local Storage Function',
    headers,
  );

  try {
    const user = JSON.stringify(userInfo);
    const userheaders = JSON.stringify(headers);
    await AsyncStorage.setItem('user', user);
    await AsyncStorage.setItem('headers', userheaders);
  } catch (e) {
    console.log('Error while storing user info', e);
  }
};

when i try to get headers from async-storage, it gave old stored headers rather than returning latest.

// Getting headers like this..

const headers = await AsyncStorage.getItem('headers');
console.log('Headers received in get Profile Action', headers);

but it returning old headers..

Upvotes: 2

Views: 691

Answers (2)

Siddharth Mishra
Siddharth Mishra

Reputation: 346

Try using the below approach to fetch the data.

const getData = async () => {
  try {
    const headers = await AsyncStorage.getItem('headers')
    return headers != null ? JSON.parse(headers) : null;
  } catch(e) {
    // error reading value
  }
}

Upvotes: 0

Muhammad Umar
Muhammad Umar

Reputation: 319

Don't know why but React native async storage is not running next line after the setItem line

await AsyncStorage.setItem('user', user);
await AsyncStorage.setItem('headers', userheaders);

setItem for a user is running but setItem for a header is not running and that's why it was returning old value

Upvotes: 1

Related Questions