I used the following function inside the Flatlist data property but it is not rendering anything. why? I think an alternative is to set state inside the function and use the state as the flatlist data property, but in that case how do I set state whenever asyncstorage changes?
async function getFlatlistData(){
try{
const numbers = await AsyncStorage.getAllKeys();
//numbers =
// ["{"key":"1678328476308","title":"Dog"}",
//"{"key":"1678328921886","title":"Cat"}"]
numbers.forEach(function myFunction(item, index, arr) {
arr[index] = JSON.parse(item);
arr[index]['key'] = Number(arr[index]['key'])
})
numbers.sort((a, b) => b.key - a.key);
console.log("running")
return numbers
} catch (error) {
alert(error)
}
}
return (
</View>
<FlatList
data={getFlatlistData()}
renderItem={
({item}) => <Text>{item.title}</Text>
}
keyExtractor={(item, index) => index.toString()}
/>
</View>
);
}
2
Answers
The FlatList component is not rendering anything because it is receiving a promise instead of an array of data.
You need to use a useState to get the array before assigning to the Flatlist.
First: You need to use useState hook to render the components.
Second: Your async function returns promise, not an array.