Niko Bellic
Niko Bellic

Reputation: 59

React Native - Unable to get data from AsyncStorage.getItem()

I am using AsyncStorage to set an Item and retrieving it using the getItem() method. My Code is as follows :

import React, { Component } from 'react';
import { View } from 'react-native';
import { Container, Left, Title, Header, Body, Right, Content, Text, Button } from 'native-base';
import AsyncStorage from '@react-native-community/async-storage';

class Counter extends Component {


  componentDidMount() {
    AsyncStorage.setItem('name' , 'abc');
  }

  getItemData() {
    console.log(AsyncStorage.getItem('name'))
  }



  render() {
    return (
      <Container>

        <Header>
          <Left />
          <Body>
            <Title>Test</Title>
          </Body>
          <Right />
        </Header>

        <Content style={{ margin: 8 }}>

          <View style={{ flexDirection: "row", alignSelf: "center" }}>

            <Button onPress={() => this.getItemData()}><Text> getItem </Text></Button>

          </View>

        </Content>

      </Container>
    );
  }

}

export default Counter;

But instead of getting "abc" in my console, I am getting this :

{"_U": 0, "_V": 0, "_W": null, "_X": null}

How to get "abc" in my console ?

Upvotes: 0

Views: 1450

Answers (2)

Burak Furkan
Burak Furkan

Reputation: 1

getItem returns a promise that either resolves to stored value when data is found for a given key or returns null otherwise.

Reading string value:

 async getAsyncData() {
      await AsyncStorage.getItem('name').then(val => {
        if(val !== null) {
          console.log(value);
        }
      })
    }

Reading object value:

 async getAsyncData() {
      await AsyncStorage.getItem('name').then(val => {
        if(val !== null) {
          console.log(JSON.parse(val));
        }
      })
    }

Upvotes: 0

Edison Pebojot
Edison Pebojot

Reputation: 318

Add async and await:

    async getItemData() {
       const result = await AsyncStorage.getItem('name');
       console.log(result);
     }

    async componentDidMount() {
       await  AsyncStorage.setItem('name' , 'abc');
     }

Upvotes: 1

Related Questions