Categories
JavaScript Answers React Native Answers

How to fix AsyncStorage fetches data after rendering issue with React Native?

Spread the love

Sometimes, we want to fix AsyncStorage fetches data after rendering issue with React Native.

In this article, we’ll look at how to fix AsyncStorage fetches data after rendering issue with React Native.

How to fix AsyncStorage fetches data after rendering issue with React Native?

To fix AsyncStorage fetches data after rendering issue with React Native, we can check if the value is fetched before rendering them item we want.

For instance, we write:

import * as React from 'react';
import { View, Text, AsyncStorage } from 'react-native';
import Constants from 'expo-constants';
import { Card } from 'react-native-paper';

export default function App() {
  const [val, setVal] = React.useState();

  const getData = async () => {
    await AsyncStorage.setItem('key', 'val');
    const v = await AsyncStorage.getItem('key');
    console.log(v);
    setVal(v);
  };

  React.useEffect(() => {
    getData();
  }, []);

  return <View>{val && <Text>{val}</Text>}</View>;
}

to call AsyncStorage.getItem with the key to get the item with the given key.

Then we call setVal to set val to the returned value.

Next, we call useEffect with a callback that calls getData and an empty array to call getData when App mounts.

And then we check if val is set before rendering Text with

val && <Text>{val}</Text>

Conclusion

To fix AsyncStorage fetches data after rendering issue with React Native, we can check if the value is fetched before rendering them item we want.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *