0

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);

1 Answer 1

1

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());
Sign up to request clarification or add additional context in comments.

7 Comments

The thing is, I need the currentDevice a few lines below to check if currentDevice has the same details as details entered in a form. So is there any way to make it wait so I can preform that check?
so you compare with doc.data()
that is correct yes. I thought this was the way to go for now because I use the details of this document later to send an email about the details of the device.
My apologies for the late response, I asked this question at the end of my shift yesterday and only started again now. It did work thank you!
note I also updated my answer for more informations
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.