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/>;
}
});
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.
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.
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 .
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With