简体   繁体   中英

AsyncStorage.getItem() returns a single value AND a promise

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?

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

由于storageGet返回了一个承诺,因此您还需要在使用它的任何地方使用await:

const value = await storageGet(key);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM