Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native wait for AsyncStorage to get value

Its a common problem, React Native trying to render before the values have been fetched from AsyncStorage. I've seen solutions for this in several places but for some reason it just doesn't work at all for me. Maybe its because I'm using React Native 25.1? It just gets stuck on 'Loading...' indefinitely. If I run a console log on render to show isLoading (without the if method) it returns false and then true so theoretically it should be working. But with the if method enabled its stuck on 'Loading' forever and also the log only returns false.

import React, { Component } from 'react';

import {
  Text,
  View,
  AsyncStorage
} from 'react-native';

  class MainPage extends Component {
   constructor(props: Object): void {
   super();
   this.state = {
     isLoading: false,
   };
 }

  componentWillMount() {
    AsyncStorage.getItem('accessToken').then((token) => {
      this.setState({
        isLoading: false
      });
    });
  }

  render() {
    if (this.state.isLoading) {
      return <View><Text>Loading...</Text></View>;
    }
    // this is the content you want to show after the promise has resolved
    return <View/>;
  }

});
like image 715
Hasen Avatar asked May 19 '16 12:05

Hasen


People also ask

Is AsyncStorage deprecated?

Deprecated. Use one of the community packages instead. AsyncStorage is an unencrypted, asynchronous, persistent, key-value storage system that is global to the app. It should be used instead of LocalStorage.

Is AsyncStorage fast?

AsyncStorage takes about 12x more time to read/write on average compared to localStorage. This article introduces a few techniques to optimize AsyncStorage so that it could be improved such that it could be used in production.

How do you use AsyncStorage in React Native functional component?

Open the App. js file and start by importing the following components. import React, {useState, useEffect} from 'react'; import { StyleSheet, View, Text, TextInput, TouchableOpacity, } from 'react-native'; import AsyncStorage from '@react-native-community/async-storage'; Next, define a variable name STORAGE_KEY .


1 Answers

Hey try this...

import React, { Component } from 'react';

import {
  Text,
  View,
  AsyncStorage
} from 'react-native';

class MainPage extends Component {

   constructor(props: Object): void {
       super(props);
       this.state = {
         isLoading: false,
       };
   }

  componentWillMount() {
    AsyncStorage.getItem('accessToken').then((token) => {
      this.setState({
        isLoading: false
      });
    });
  }

  render() {
    if (this.state.isLoading) {
      return <View><Text>Loading...</Text></View>;
    }
    // this is the content you want to show after the promise has resolved
    return <View/>;
  }
}

Let me know if you need more clarifications...

like image 113
Jickson Avatar answered Sep 28 '22 15:09

Jickson