Im working on a mapping application where i need to display markers on a map. When the map viewable area (bounds) changes i am fetching from the server the items that should be displayed as markers for said area. So basically, when the map bounds change, fetch items for new bounds from the server using useLazyQuery.
I want to be more efficient though and only fetch new items from the server where the bounds are outside the bounds we have already fetched items for. For example, if the user pans the map 10% to the right we already have 90% of the data in the cache so i only want to fetch this new 10% of the bounds instead of fetching everything within the new bounds.
My question is, when i do a new fetch via usingLazyQuery to only get the remainding 10% of the map that we dont know about, the data value is only going to contain that data and my components that are using the query data will only contain this 10% of data. Is there any way to append the results of useLazyQuery to the existing data instead of replacing it?
Im returning the data returned from the query as an array of components, but i need to return the data returned from the query PLUS the data already returned from previously queries.
Perhaps i could useRef to hold the combined results and then append the new query results to the ref?
Yep, what you’re looking for is a merge
typePolicy
. This documentation should put you on the right track: Customizing the behavior of cached fields - Apollo GraphQL Docs
What ive done (and seems to be working well) is to keep the overall data in a seperate state variable, and then when my useLazyQuery completes i use onCompleted to merge in the new result to the current known state. Do you think your merge typepolicy would be a better solution i should switch to?
It depends - type policies do have the advantage of providing a central place for defining how types are handled, so whenever your server returns objects of that type, the merge type policy will do its thing. If you only have a single query for your map markers, then your solution is completely fine.