Search code examples
javascriptreact-nativereact-hooksreact-native-flatlist

Each child in a list should have a unique "key" prop, I am getting this error in my react native app


I am getting the below errors when I tried to fetch array data from firebase firestore. How can I solve this issue could someone please suggest me the code structure.

VM22 bundle.js:3927 Warning: Each child in a list should have a unique "key" prop.

Check the render method of CellRenderer. See https://reactjs.org/link/warning-keys for more information. at http://localhost:19006/static/js/bundle.js:157320:19 at CellRenderer (http://localhost:19006/static/js/bundle.js:172017:36)

import React, { useState, useEffect } from 'react';
import {View, Button, Text, FlatList, StyleSheet, Pressable, TouchableOpacity} from 'react-native'
import {firebase} from '../config';

const Testing = ({ navigation }) =>{
    const [users, setUsers] = useState([]);
    const todoRef = firebase.firestore().collection('testing');
  

    useEffect(() => {
        todoRef.onSnapshot(
            querySnapshot => {
                const users = []
                querySnapshot.forEach((doc) => {
                    const {  ArrayTesting
              
                    } = doc.data()
                    users.push({
                        id: doc.id,
                        ArrayTesting
                      
                    })
                })
                setUsers(users)
            }
        )
    }, [])
return (

   <View style={{ flex:1,}}>
   <FlatList 
 data={users}
  numColumns={1}
  renderItem={({item}) => (

    <Pressable >
<View>

  <View>
{ (item.ArrayTesting) 
  ? item.ArrayTesting.map((item) => <Text>{item}</Text>) 
  : <Text></Text>
}

</View>

</View>
 </Pressable>
     )} />
</View>
);}
export default Testing;

Solution

  • While you are mapping components in react, you have to provide unique key for the components, so it will know which component to rerender.

       <View>
    { (item.ArrayTesting) 
      // if item has unique field, please provide that as key in Text
      ? item.ArrayTesting.map((item,index) => <Text key={index}>{item}</Text>) 
      : <Text></Text>
    }
    
    </View>