1

I have a problem that I can not solve try a thousand ways and nothing

I happen to show

I generate a state:

 const [totalComidas, setTotalComidas] = useState({})

After that I do a useEffect to bring me the data from firebase and I want to save it in the state but it saves it empty

useEffect(() => {

    const resultadoComidas = []
    db.collection('menu semanal')
    .get()
    .then((snap) => {
        snap.forEach((doc) => {
           const comida = doc.data()
        //    comida.id = doc.id
           resultadoComidas.push(comida)
           console.log(resultadoComidas[0])
        })
        setTotalComidas(resultadoComidas)
        console.log(totalComidas) 
    })    
}, [])

And these are my results in console

enter image description here

The first result in the console is before adding it to the state and the second is the new state, which seems strange to me because it brings the data correctly but when I assign it to the state it assigns it to me empty.

1 Answers1

0

It's normal for the totalComidas to be empty when you log it inside useEffect because the result of your setTotalComidas won't be showed in that particular useEffect. If you want to see the change of your totalComidas you need to have another useEffect like so

useEffect(() => {
   console.log(totalComidas)
})

If you wonder why this is the case then read this. It explains the behavior of useEffect

kunquan
  • 1,127
  • 1
  • 10
  • 24