简体   繁体   中英

Get array of objects from real time data snapshot - Cloud Firestore

I'm trying to fetch real time data from Cloud Firestore using the below code.

export const getRealTimeData = () =>
  db
  .collection('posts')
  .onSnapshot(
    (querySnapshot) => {
      const posts: any = [];
      querySnapshot.forEach((doc) =>
        posts.push(Object.assign({
          id: doc.id
        }, doc.data()))
      );
    },
  );
};

And, I want to use the resultant array to display the data on UI. When I'm doing this, the resultant array is a function but not the actual array of data.

const posts = getRealTimeData();

Here's what I get when I log posts

function () {
  i.kT(), o.al(s);
}

Could anyone please point where I went wrong?

Realtime listeners added with onSnapshot() are not compatible with returning values from function calls. That's because they continue to generate new results over time, and would never really "return" anything once. You should abandon the idea of making a synhronous getter type function in this case - they just don't work for what you're trying to do.

Ideally, you would use an architecture like Redux to manage the updates as they become available. Your realtime listener would dispatch query updates to a store, and your component would subscribe to that store that to receive those updates.

If you don't want to use Redux (which is too bad - you really should for this sort of thing), then you should wrap your query inside a useEffect hook , then have your listener set a state hook variable so your component can receive the updates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM