RandomDeveloper
RandomDeveloper

Reputation: 873

Firebase promise - unable to set state, state array is empty

I have a promise to get a firebase collection and then return respective data (all according firebase documentation).

The data is returning fine, the only problem is that it seems that I am unable to set the collection data to a state array. When console.log(chats)this returns an empty array.

The data is returning fine as adding a console.log(doc.data()) in the first then logs the data ok but then it is empty.

What am I doing wrong in the promise?

const HomeScreen: React.FC<Props> = ({ navigation}) => {
  const [chats, setChats] = useState<{[key: string]: any}>([]);

useEffect(() => {
  const chatsArray = [{}];
  db.collection("chats")
  .get()
  .then((querySnapshot) => {
     querySnapshot.forEach((doc) => {
          chatsArray.push({
            id: doc.id,
            data:doc.data(),
          })
      });
  })
  .then(() => {
    setChats(chatsArray)
    console.log(chats);
 })
  .catch((error) => {
        console.log("Error getting documents: ", error);
    });
}, []);
 
  return (
    <SafeAreaView>
      <ScrollView style={styles.container}>
       {chats go here}
      </ScrollView>
    </SafeAreaView>
  )
}
export default HomeScreen;

Upvotes: 0

Views: 69

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598623

The console.log(chats); doesn't work, since updating the state is a asynchronous operation that won't have completed by the time you log the value. Try console.log(chatsArray); to see the actual value.


In addition, consider passing the array as the result along the promise chain instead of using a variable in the context:

db.collection("chats")
.get()
.then((querySnapshot) => {
   return querySnapshot.docs.map((doc) => {
      return {
        id: doc.id,
        data:doc.data(),
      }
    });
})
.then((chatsArray) => {
  setChats(chatsArray)
  console.log(chatsArray);
})
.catch((error) => {
  console.log("Error getting documents: ", error);
});

Or simpler and with the same result:

db.collection("chats")
.get()
.then((querySnapshot) => {
    const chatsArray = querySnapshot.docs.map((doc) => {
    chatsArray.push({
      id: doc.id,
      data:doc.data(),
    })
  });
  setChats(chatsArray)
  console.log(chatsArray);
})
.catch((error) => {
  console.log("Error getting documents: ", error);
});

Upvotes: 1

Related Questions