I've got a question, how can I load data from asyncStorage to my FlatList after I reload the app?Here is my screen, where I have the data, FlatList and asyncStorage:
import { StatusBar } from 'expo-status-bar';import React, {useState, useEffect} from 'react';import { StyleSheet, Text, View, Button, FlatList, Alert,} from 'react-native';import AsyncStorage from '@react-native-community/async-storage';import GoalItem from'../components/Goalitem';import colors from '../constants/colors';type Props={ navigation:any}const MainScreen = (props:Props) =>{ const input: string = props.navigation.getParam('input'); const [products, setProducts] = useState<any>([]); const storeData = async(id:string, value:string) =>{ try{ const product ={ productId: id, productName: value } const existing_products:any = await AsyncStorage.getItem('stored_products'); let new_product:any = JSON.parse(existing_products); if(!new_product) { new_product = []; } new_product.push(product); await AsyncStorage.setItem('stored_products', JSON.stringify(new_product)); console.log(new_product); } catch (err){ alert(err); }};useEffect( () => { let douledvalue:string = ''; let id:string = Math.random().toString(); if(input !== undefined && douledvalue !== input) setProducts([...products,{id: id, value: input}]); if(input !== null && input !== undefined) { storeData(id ,input); }}, [input]) function removeGoalHandler(goalId:any):void { setProducts((courseGoals: any[]) => { return courseGoals.filter((goal:any) => goal.id !== goalId); }); }; function deleteListAlert():void { if(products.length >0) { Alert.alert('Lista zostanie wyczyszczona!','Czy aby na pewno chcesz wyczyścić liste?', [{text: 'Tak', style: 'destructive', onPress: deleteList}, {text: 'Nie', style: 'cancel'}]); } else{ Alert.alert('Lista jest pusta.','W liście nie ma żadnych przedmiotów.', [{text: 'Powrót', style: 'cancel'}]); } } function deleteList() { setProducts(''); } return (<View style = {styles.screen}> <FlatList style = {styles.flatListPosition} keyExtractor={(item, index) => item.id} data = {products} renderItem ={itemData => (<GoalItem id = {itemData.item.id} onDelete = {removeGoalHandler} title = {itemData.item.value} /> )} /><View style = {styles.buttonPosition}><View style = {styles.button1}><Button color = {'mediumaquamarine'} title = "WYCZYŚĆ" onPress={deleteListAlert}/></View><View style = {styles.button}><Button color = {'mediumaquamarine'} title="+" onPress = {() => { props.navigation.navigate('Adding') }}/></View></View></View> );}MainScreen.navigationOptions = { headerTitle: 'Lista zakupów', headerStyle:{ backgroundColor: 'mediumaquamarine' }, headerTintColor: 'white'};const styles = StyleSheet.create({ screen:{ flex:1, backgroundColor: 'white', }, button:{ width: 40, }, button1:{ width: 90, }, buttonPosition:{ padding:15, alignItems: 'stretch', justifyContent: 'space-between', flexDirection:'row', //backgroundColor: 'transparent' }, flatListPosition:{ padding: 8, }});export default MainScreen;
Here I'm adding data to async:
const storeData = async(id:string, value:string) =>{ try{ const product ={ productId: id, productName: value } const existing_products:any = await AsyncStorage.getItem('stored_products'); let new_product:any = JSON.parse(existing_products); if(!new_product) { new_product = []; } new_product.push(product); await AsyncStorage.setItem('stored_products', JSON.stringify(new_product)); console.log(new_product); } catch (err){ alert(err); }};
I don't know if it's possible but I must keep the state of the list in products:
const [products, setProducts] = useState<any>([]);
But after reloading app, upload the data from asyncStorage to FlatList (it's not my idea, i've got this in requirements :D)