Home > Blockchain >  React function does not await data from Firestore
React function does not await data from Firestore

Time:01-27

Everytime I run the following code React seems to continue and not fill the CurrentDevice as I asked in setCurrentDevice. It just throws an undefined in the log when asked on the last line. It does seem to log the correct device details as I can see when the first console.log runs. How do I make react fill the state CurrentDevice before continuing?

const q = query(collection(db, 'DeviceDetails'), where('serialNo', '==', SerialNo))

    const querySnapshot = await getDocs(q)
    querySnapshot.forEach((doc) => {
      // doc.data() is never undefined for query doc snapshots
      setCurrentDevice(doc.data());
      console.log(doc.data());
    })

    console.log(currentDevice);

CodePudding user response:

when you update a hook as useState in this example the component re-render with the new value of the hook so currentDevice will get the new value during the next render it's not available yet. try to consol.log('this is a new render and this is my data : ',currentDevice) from inside your jsx to understand better.

note also, that here with your code, you are only storing the last item of querySnapshot inside your currentDevice not all the items because on every itteration you are overwritting the value so it will end only with the last one, I don't know what you are trying to do but I don't think this is what you want to achieve, if you want to store them all, this is the right way

const querySnapshot = await getDocs(q)
setCurrentDevice(querySnapshot.map((doc) => doc.data()));

but if you really want to store only the last item better to do it like this :

const querySnapshot = await getDocs(q);
setCurrentDevice(querySnapshot[querySnapshot.length- 1].data());
  • Related