Taylon Assis
Taylon Assis

Reputation: 343

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?

Upvotes: 7

Views: 10607

Answers (2)

Nikhil Parmar
Nikhil Parmar

Reputation: 499

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

Upvotes: 6

Matt Aft
Matt Aft

Reputation: 8936

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

const value = await storageGet(key);

Upvotes: 5

Related Questions