Apollo Graphql: How to prevent refetch function from fetching all the records if same variables are provided
I'm using Apollo GraphQL client to fetch the data from Shopify storefront APIs. There is a marketplace page which lists all the products and a filter panel.
I'm using Apollo client's useLazyQuery
to avoid the very first fetch on the component initialization, rather I use refetch
in the useEffect
providing all the initial filters as variables. I also use relayStylePagination
for cursor based pagination of the records.
function ProductsList() {
const [_, {data, loading, refetch, fetchMore}] = useLazyQuery(PRODUCTS, {
collection: 'featuredProducts'
});
const productEdges = data?.collection?.products?.edges;
const pageInfo = data?.collection?.products?.pageInfo;
const loadMoreProducts = React.useCallback(() => {
if (pageInfo?.hasNextPage) {
fetchMore({
variables: {
cursor: pageInfo.endCursor,
},
});
}
}, [fetchMore, pageInfo?.endCursor, pageInfo?.hasNextPage]);
React.useEffect(() => {
refetch({
filters: filters
})
}, [filters]);
return <div>
<ListProducts products={productEdges} />
<Button onClick={loadMoreProducts}>Load More</Button>
</div>
}
The problem is, when I fetch five pages by clicking on the Load More button, visit one of the last products detail page, come back on the listing page, I don't see all the previous records. The refetch
again fetches the first set of products. I don't want the refetch
to fetch products if they are already there in the cache for same filters (including pagination).
I tried various fetchPolicy
and nextFetchPolicy
options but none of them worked.
Comments
Post a Comment