Search code examples
javascriptreactjsreact-nativesetstateasyncstorage

React Native load state from Async storage on start


State "reminders" saved to AsyncStorage with key "reminders". Now I need to load "reminders" from AsyncStorage with key "reminders" every time App started. And then show it in a FlatList.

How I can do this?

import React, {useState, Component} from 'react';
import {
  StyleSheet,
  Text,
  View,
  SafeAreaView,
  FlatList,
} from 'react-native';
import {AsyncStorage} from 'react-native';

function Reminders() {

  // REMINDERS
  const [reminders, setReminders] = useState([
    {day: 'MON', time: new Date(), status: true},
    {day: 'TUE', time: new Date(), status: true},
    {day: 'WED', time: new Date(), status: true}
  ]);

  return (
    <View>
      <FlatList
        data={reminders}
        renderItem={({item, index}) => (
          <View><Text>{item}</Text></View>
  );
}
export default Reminders;

Solution

  • you can use the hook useEffect:

    useEffect(readReminders, []);
    
    function readReminders() {
        AsyncStorage.getItem('reminders').then(value=> setReminders(value));
    }