I’m new with react native. I’m using a flatlist to render data from firebase (v9).
Everything works well, there isn’t any error but, the list show only one item. After searching on differents topic, I think the problem is from the keyExtractor. But i don’t know how to solve it.
The Key Extractor from the code :
keyExtractor={item => item.id}
Here is the code :
const Liste = () => { const [users, setUsers] = useState([]); const [currentPage, setCurrentPage] = useState(1); const [isLoading, setIsLoading] = useState(false); const querySnapshot = await getDocs(collection(db, "form")); querySnapshot.forEach((doc) => { setUsers([...users, doc.data()] ); }); } const renderItem = ({ item }) => { return( <View> <View> <Text>{`${item.Address}`}</Text> <Text>{`${item.Prix}`}</Text> <Text>{`${id}`}</Text> </View> </View> ); }; const renderLoader = () => { return ( isLoading ? <View style={styles.loaderStyle}> <ActivityIndicator size="large" color="#aaa" /> </View> : null ); }; const loadMoreItem = () => { setCurrentPage(currentPage + 1); }; return ( <View <StatusBar backgroundColor="#000" /> <FlatList data={users} renderItem={renderItem} keyExtractor={item => item.id} ListFooterComponent={renderLoader} onEndReached={loadMoreItem} onEndReachedThreshold={0} /> </View> )} export default Liste;
Firestore :
The screen of the app :
Can you please help me ?? Thanks a lot !!
Advertisement
Answer
The recommended best practice is to run side effects like fetch data from server inside useEffect
hook.
const Liste = () => { const [users, setUsers] = useState([]); const [currentPage, setCurrentPage] = useState(1); const [isLoading, setIsLoading] = useState(false); const getUsers = async () => { let result = []; const querySnapshot = await getDocs(collection(db, "form")); querySnapshot.forEach((doc) => { result.push(doc.data()); }); setUsers([...result]); }; useEffect(() => { getUsers(); }, []); const renderItem = ({ item }) => { return ( <View> <View> <Text>{`${item.Address}`}</Text> <Text>{`${item.Prix}`}</Text> </View> </View> ); }; const renderLoader = () => { return isLoading ? ( <View style={styles.loaderStyle}> <ActivityIndicator size="large" color="#aaa" /> </View> ) : null; }; const loadMoreItem = () => { setCurrentPage(currentPage + 1); }; return ( <View> <StatusBar backgroundColor="#000" /> <FlatList data={users} renderItem={renderItem} keyExtractor={(item) => item.id} ListFooterComponent={renderLoader} onEndReached={loadMoreItem} onEndReachedThreshold={0} /> </View> ); }; export default Liste;