Reputation: 4631
Suppose that in my app, several components fetch the same data from Firestore: they fetch the documents of the same collection with the same filters and limits.
The app has 3 pages, 2 of them render the components that need the firestore data (the red nodes: AA and D). Page 2 does not need the data:
If I duplicate the query.onSnapshot
in AA and D, does the Firestore JS SDK hold a global cache or does it fetch the data twice?
Should I put the query in the first common ancester, ie Router, at the expense of loading data even if only Page2 is used?
What is the best way to implement this?
I know that we can fetch the data in the first common ancestor and pass it down with prop drilling, redux, or React.Context. This is not the point of my question.
I am specifically asking in the context of fetching Firestore data: since there exist a cache (for offline or cache first query), is there a trick to allow querying the data only if needed, and only once?
Upvotes: 2
Views: 297
Reputation: 684
You can make an empty state of data in router and write a logic to fetch the data in a function in router which after fetching updates the data in state.
// in router.js
const [data, setData] = useState(null)
const fetchData = () => {
const apiResponse = getResponseFromAPI()
setData(apiResponse)
}
Pass this state and function as prop to AA and D component.
In the useEffect of AA and D check if data is present then don't call the function
// in AA component
useEffect(() => {
if(!data){
fetchData()
}
},[])
In this way you will only fetch the data when its necessary and it will be fetched only once
Upvotes: 1