Reputation: 1181
I'm using React and Next.js with Firestore. On one page I get data from Firebase with useEffect only once the page is rendered. But since the get is kind of costly (lots of read), I want to persist the data fetched even when the user navigates to other pages and back to this page, so that I don't need to fetch again. How can I do that? Thanks!
useEffect(() => {
var newObj = {};
FB.getAllFiles()
.then((snapshot) => {
snapshot.forEach((doc) => {
const data = doc.data();
newObj[data["name"]] = data["count"];
});
})
.then(() => {
setCounts(newObj);
})
.catch((e) => console.log(e));
}, []);
Upvotes: 0
Views: 347
Reputation: 7408
As explaied in the other answers use the context and to make it even better you can persist the realtime listeners by controlling when you want to start or stop theme. Here is an example of Providers made for Firebase that do exactly the same. They also enable offline working for PWAs and persist state between reloads.
It's importand to understand that if you don't persist the realtime listeners you won't have any benefit from storing the data into any local state. Calling the listener again would load all data again and cost you the same. The only benefit from that would be that the user has the local data initial so it looks like the app is faster.
Upvotes: 1
Reputation: 1051
There are multiple ways but one good way would be to use Context, create a data store context which would store your data and then you can read from it as a single source of truth.
Upvotes: 1