7

I'm trying to get a single value kept in my device by a AsyncStorage.setItem(KEY, VALUE);.

I have this localStorage.js file to manage local data

import React from 'react';
import { AsyncStorage } from 'react-native';

const storageSet = async(key, value) => {
    try {
      await AsyncStorage.setItem(key, value);
    } catch(error) {
      console.log(error);
    }
}

const storageGet = async(key) => {
  try {
       const result = await AsyncStorage.getItem(key);
       console.log(result);
       return result;
    } catch(error) {
      console.log(error);
    }
}

export { storageSet, storageGet };

In login.js file I call these functions passing the parameters. It saves right. But when I try to getItem() values I have two distinct returns, a promise AND a single value. Follow:

console.log(result) whithin storageGet('key'), it's what I want.

57d7bc714b269533
1
ASUS_Z00AD
1.0
null
1

console.log(result) out storageGet('key') function. In main.js, when I call it.

{login: "Hh", senha: "Hu", imei: Promise, tipo: Promise, modelo: Promise, …}
imei:
Promise {_40: 0, _65: 1, _55: **"57d7bc714b269533"**, _72: null}
login: "Hh"
mobile_key:
Promise {_40: 0, _65: 1, _55: **null**, _72: null}
mobile_push:
Promise {_40: 0, _65: 1, _55: **"1"**, _72: null}
modelo:
Promise {_40: 0, _65: 1, _55: **"ASUS_Z00AD"**, _72: null}
senha: "Hu"
tipo:
Promise {_40: 0, _65: 1, _55: **"1"**, _72: null}
versao:
Promise {_40: 0, _65: 1, _55: **"1.0"**, _72: null}
__proto__: Object

PS.: some items up there is not a return from getItem().

Why does not it just return the single value?

0

2 Answers 2

6

AsyncStorage saves data only as strings. You just need to use JSON.stringify() when saving and JSON.parse() when retrieving.

AsyncStorage.getItem('key')
.then((value) => {
  const data = JSON.parse(value);
  console.log('name is ', data.name);
});
5

Since storageGet returns a promise, you need to also use await anywhere you use it:

const value = await storageGet(key);
3
  • using await only produces the following error TypeError: bundle.added is undefined[Learn More]
    – Ren
    Commented Apr 29, 2019 at 19:50
  • @Yokhen that sounds like an error that has nothing to do with using await.
    – Matt Aft
    Commented Apr 29, 2019 at 20:45
  • Yeah I think it has to do with AsyncStorage
    – Ren
    Commented Apr 29, 2019 at 20:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.