Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

How to read local storage data in useEffect hook in React Native

$
0
0

I am trying to get data from my local storage by using useEffect before rendering any components. I am using the data from the local storage for my flatlist however, when i try this my flatlist is empty.

When the dependencies for useEffect is empty, my flatlist is empty. When i have allKeys as the dependency i get multiple promises.I believe the issue is the useEffect hook as i am able to get the data correctly when i am not using useEffect by using async functions, however i need to be able to update the flatlist when ever the page is rendered again which is why i need to use useEffect.

My code:

const [allKeys, setGetLocalStorageKeys] = useState([]);const [arrayItems,setArrayItems] = useState([]);let arrayItems= [];const getLocalStorageKeys = async () => { try {  setGetLocalStorageKeys(await AsyncStorage.getAllKeys()); } catch (e) {}};const getItem = async (prop) => {try {  const item= await AsyncStorage.getItem(prop);  return item != null ? JSON.parse(item) : null;  } catch (e) {}};useEffect(() => {try {  getLocalStorageKeys();  const tempArr = [];  for (let i = 0; i < allKeys.length; i++) {    tempArr.push(getItem(allKeys[i]));  }  setArrayItems(tempArr);} catch (e) {}}, []);return (<View><FlatList    data={arrayItems}    renderItem={({ item }) => <Text>{item}</Text>}    keyExtractor={(item) => item}  /></View>);

Local Storage https://github.com/react-native-async-storage/async-storage


Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>