Fede Falour
Fede Falour

Reputation: 1

Can't get data stored with AsyncStorage

I'm a newbie, and I came up with a problem: I've managed to store data in the device using AsyncStorage. The thing is, that when I invoke the read method in my wrapper, I can see that the data is there, as I log everything inside the await. But when I use that that to make a POST request, the data I get on the other side, has absolutely nothing to do with what I've saved.

Here's some code for you guys:

  1. Here's the wrapper I'm using to save and read data:

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

module.exports = {
  save: async function(key, data){
    //console.log(save key:${key} data:${data} stringify:${JSON.stringify(data)});
    try {
      await AsyncStorage.setItem(key, JSON.stringify(data));
      console.log('### STORAGE - Save: Saved key: ' + key + ' with data ' + data)
      return true;
    } catch(err) {
      console.log('### STORAGE - Save: ERROR SAVING ' + key + ':' + data);
      return false;
    }
  },
  read: async function(key) {
    console.log('### STORAGE - Reading key: ' + key);
    try {
      var data = await AsyncStorage.getItem(key);
      if (data !== null){
        console.log('### STORAGE - Read result: ' + typeof(JSON.parse(data)) + ' : ' + JSON.parse(data));
        return JSON.parse(data);
      }else {
        console.log("### STORAGE - Storage.read(): Not found");
        return false;
      }
    } catch (err) {
      console.log('### STORAGE - Storage.read(): error: ' + err.message);
      return false;
    }
  },
  empty: function(key){
    try {
      AsyncStorage.setItem(key, '');
      //console.log(Storage.empty: cleaning key ${key});
      return true;
    } catch(err) {
      //console.log(Storage.empty: ERROR ${err});
      return false;
    }
  }
}

  1. Here's the function I'm using to retrieve data:

  _onPressButtonGET() {
    var usuario = storage.read('lastname');
    return fetch("http://<my api>", {
      method: "POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        username: usuario,
        lastname: 'yourOtherValue',
        cellphone: 'cellphone',
        parse: 'parse',
      })
    })
    .then((response) => response.json())
    .then((responseJson) => {
      console.log(responseJson)
      Alert.alert(
          "GET Response",
          "EMERGENCY " + JSON.stringify(responseJson['EMERGENCY'])
      )
    })
    .catch((error) => {
      console.error(error);
    });
  }
}

Now, when I see the logs from the storage wrapper, I get the following:

I/ReactNativeJS(15760): ### STORAGE - Reading key: username
I/ReactNativeJS(15760): ### STORAGE - Read result: string : Federico

This means, that the data IS THERE!! =)

But, when I make the POST request with the value I just recovered, this is what I get in the API logs:

BODY: {u'username': {u'_40': 0, u'_72': None, u'_55': None, u'_65': 0},

I just can't see what I'm doing wrong. Is that a promise? If that so, can someone give a detailed example about how it should be handled? Sorry about this, but I'm stuck with this for a while now =(

Upvotes: 0

Views: 2685

Answers (1)

Andreyco
Andreyco

Reputation: 22872

Your "read" method is async, returns Promise under the hood.

read: async function(key) {
  // ...
},

To read value, either await for promise to resolve, or use .thens.

async _onPressButtonGET() {
  var usuario = await storage.read('lastname');
  // ...
}

Upvotes: 3

Related Questions