I am creating a messaging board feature within my application using GraphQL and Apollo State Management.
My problem is that I want to update the cache directly but due to pagination / infinite scrolling I am running into issues
update: (cache, { data }) => {
const commentQuery: any = cache.readQuery({
query: QUERY,
variables: {
page: 1,
limit: 8,
shortlistId: Number(id),
},
});
const currentComment = commentQuery?.getCommentQuery?.comments?.find((item) => item?._id === data?.createComments?.reply_to);
cache.writeQuery({
query: QUERY,
variables: {
page: 1,
limit: 8,
shortlistId: Number(id),
},
data: {
getCommentQuery: {
...commentQuery?.getCommentQuery,
comments: [
...commentQuery?.getCommentQuery?.comments,
{
...currentComment,
...currentComment?.replies,
comments: [...currentComment?.replies?.comments, ...(Array.isArray(data?.createComments) ? data?.createComments : [])],
},
],
},
},
});
because apollo wants the variables to be the same as stored in cache my read / write to cache update function works perfectly when I am on the page:1 as thats whats stored in cache
my problem is when i am on page: 5 and try this i will get an error as my readQuery returns null due to the data being different from cache
I also tried this approach
const cacheId = cache.identify(data?.createComments);
cache.modify({
fields: {
commentQuery: (prev, { toReference }) => {
return [prev, toReference(cacheId ?? "")];
},
},
});
but i am running into similar issues