Home > Back-end >  Encountered two children with the same key - React Native Gifted Chat
Encountered two children with the same key - React Native Gifted Chat

Time:03-21

The bellow code runs somewhat to what I want. I'm able to get the correct data when i enter the component, but as soon as I send a message, it duplicates the previous messages. I'm quite new to React Native so just learning. Any help or suggestions would be appreciated!

1.) Fetch documents where 'selectedUser (local) == field 'to' in Firebase.

2.) Display chats from the found documents.

3.) Send message to screen and firebase.

4.) Profit.

useEffect(() => {

    const q = query(collectionRef, orderBy('createdAt', 'desc'));

    const unsubscribe = onSnapshot(q, querySnapshot => {
      
      const id =  querySnapshot.docs.map(doc => ({
        _id: doc.data()._id,
        createdAt: doc.data().createdAt.toDate(),
        text: doc.data().text,
        user: doc.data().user,
        to: doc.data().to
        
      }))

      id.forEach((val)=>{

        if(val.to == selectedUser[0]){
          console.log(val.to)
          DATA.push({
          _id: val._id,
          createdAt: val.createdAt,
          text: val.text,
          user: val.user,
          to: val.to,
          }
          );
        }

      })
      // console.log(DATA)

      setMessages(DATA);
      // console.log(Message)
    });

    return () => unsubscribe();
  }, []);


  const onSend = useCallback((messages = []) => {
    const to = selectedUser.toString();
    const { _id, createdAt, text, user } = messages[0]
   

    addDoc(collection(db, 'Chats'), { _id, createdAt,  text, user, to });
}, []);



  return (
  <SafeAreaView style={styles.container}>
    <Text style={styles.ChattingWith}>Chatting with: {selectedUser[[0]]}</Text>


    <View style={styles.MainFeed}>

    <GiftedChat
            messages={messages}
            showAvatarForEveryMessage={true}
            onSend={messages => onSend(messages)}
            user={{
                _id: auth?.currentUser?.email,
                avatar: auth?.currentUser?.photoURL
            }}
        />

    </View>



  </SafeAreaView>
  )
}

What Firestore has when 'onSend' function is called:

enter image description here

CodePudding user response:

can you try replacing

       id.forEach((val)=>{

        if(val.to == selectedUser[0]){
          console.log(val.to)
          DATA.push({
          _id: val._id,
          createdAt: val.createdAt,
          text: val.text,
          user: val.user,
          to: val.to,
          }
          );
        }

      })
setMessages(DATA);

with

const newData = id.filter((val)=> val.to == selectedUser[0])
setMessages(newData);

  • Related