1

the first bit gets the id and puts it into "id List" and shows it is doing this with the console.log of (doc.data()) (and other things i have no included that prove this.)

the second bit console.log(idList) shows it as empty.

How can i include a console.log(idList) with the doc.data() in it, within the useEffect?

 useEffect(  ()=>{
        firestore.collection("Selection").doc(me.uid).collection("id").get()
    .then( (querySnapshot) => {
    querySnapshot.forEach(doc  => { 
    //    console.log(doc.id, " => ", doc.data());
       setIdList([...idList, doc.data()]);
       x= idList;
       console.log("first",x, idList, doc.data())
    })
    
    }).then(()=>{
        console.log("second",idList)
        // Load();
    });
    /// IdList has the list of id's
    },[])
Alexander Hemming
  • 753
  • 1
  • 6
  • 28
  • Setting state is an asynchronous operation. If you want to respond to the setting of `idList`, you'll need another `useEffect` hook: https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately – Frank van Puffelen Mar 01 '21 at 15:55
  • i tried to double upvote your comment but now it unupvoted it and I cant upvote it again D: – Alexander Hemming Mar 01 '21 at 17:49
  • 1
    No worries. I was mostly waiting to hear if that allowed you to solve it, before linking the question. Just did that now, and thanks for providing your own answer on how you used that approach here. – Frank van Puffelen Mar 01 '21 at 22:38

1 Answers1

0

As the comment stated.

Setting the state is async.

this means that the event loop will mean they will not go in the ".then" order.

the solution is to create another useEffect such as this.

old code changed:

useEffect(  ()=>{
        firestore.collection("Selection").doc(me.uid).collection("id").get()
    .then( (querySnapshot) => {
    querySnapshot.forEach(doc  => { 
    //    console.log(doc.id, " => ", doc.data());
       setIdList([...idList, doc.data()]);
       x= idList;
       console.log("first",x, idList, doc.data())
    })
    
    }).then(()=>{

    });
    /// IdList has the list of id's
    },[])

new additional code

useEffect(()=>{
if (idList.length+1 >1) {
        console.log("second",idList)
        // Load();}
},[idLis]) 

or a much smarter way :

useEffect(()=>{
firestore.collection("Selection")
.doc(me.uid).collection("id").get()
.then( (querySnapshot) => {
const newIdList = [...idList]
querySnapshot.forEach(doc => {
newIdList.push( doc.data() )
})
return newIdList
})
.then( newIdList => {
return firestore.collection( ‘users’ ).load( idList )
})
.then( users => {
console.log( users )
})
Alexander Hemming
  • 753
  • 1
  • 6
  • 28