1

I have a list and everytime a child is added on firebase I want to get that child and add it to the list but for some reason it is adding the same child twice.

const [list, setList] = useState([{name:"Raja",age:5,count:10,dineIn:false,takeOut:true,black:false,white:true,asian:false,hispanic:false,other:false,male:true,female:false,zipcode:60645},
  {name:"Mano",age:5,count:10,dineIn:false,takeOut:true,black:false,white:true,asian:false,hispanic:false,other:false,male:true,female:false,zipcode:60645},
  {name:"Tom",age:5,count:10,dineIn:false,takeOut:true,black:false,white:true,asian:false,hispanic:false,other:false,male:true,female:false,zipcode:60645},]);


  const addToList = (newItem) => {
    setList((prevList) => [...prevList, newItem]);
  };

  useEffect(() => {
    onChildAdded(userRef,(data) =>{
        addToList(data.exportVal());
      })
  }, [])
  ext

I tried using an if statment to check if the data passed into childadded is different from the pervious but that didn't work.

I tried simply just changing a variable to the new data and then useEffect to check if the data is different and then add it.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Ryan Allan
  • 11
  • 1
  • The most likely cause would be that you're calling `onChildAdded` twice, and thus adding two listeners. You might want to double check your code for that. – Frank van Puffelen May 06 '23 at 15:00
  • I'm sure im calling the function itself once, is there any other reason this would occur? – Ryan Allan May 06 '23 at 15:50
  • With `StrictMode`, React calls your effect handler twice on mount in development mode. Go through the linked thread's answer to understand more, but basically, you need a clean-up function that would remove the `onChildAdded` before the component gets unmounted. – Youssouf Oumar May 06 '23 at 16:50

0 Answers0