I am learning apollo and graphQL and have a simple application that displays a list of data, with a fetchMore function that adds to the array.
I would like to remove the updateQuery as it is being deprecated and use the new field policy merge function. The current cache setup and updateQuery looks like this:
const cache = new InMemoryCache({
typePolicies: {
client_client: {
fields: {
// add local only value to clients
isEdited: {
read(value = false) {
// when writing the new value return new value or false as default
return value;
},
}
}
}
}
});
const onFetchMore = () => {
fetchMore({
variables: {
offset: page
},
updateQuery: (previousResult, { fetchMoreResult, queryVariables }) => {
return {
...previousResult,
client_client: [
...previousResult.client_client,
...fetchMoreResult.client_client,
],
};
},
});
}
However I cannot seem to get it to work as a merge function within the cache for apollo client v3. I have tried adding the merge in many different places however it always seems to break the application.
Any help on how to do this would be appreciated.
According to the docs, define field policy within the typePolicies
option provided in the InMemoryCache
constructor:
const cache = new InMemoryCache({ typePolicies: { Query: { fields: { feed: { // Don't cache separate results based on // any of this field's arguments. keyArgs: false, // Concatenate the incoming list items with // the existing list items. merge(existing = [], incoming) { return [...existing, ...incoming]; }, } } } } })
Then you just pass the offset
and limit
to the initial query:
const { loading, data, fetchMore } = useQuery(GET_ITEMS, { variables: { offset: 0, limit: 10 }, });
and fetchMore
to get the next iteration:
fetchMore({ variables: { offset: 10, limit: 10 }, });
Checkout the docs here: https://www.apollographql.com/docs/react/pagination/core-api/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With