apollographql / apollographql/apollo-client
updating cache when the data resides in a sub field
- Dominant language
- TypeScript
- Stars
- 19.8k
- Forks
- 2.9k
- Avg merge
- 11h 14m
- Merged PRs (30d)
- 18
Description
Consider a scenario where my query is simple and I had to update my cache after a mutation.
https://gist.github.com/Yasir5247/a3e6cc399dc166d877ff00cc68a1e093
This is simple and easy to implement. however the following query
```
query GetComments($productId: Int!, $limit: Int!, $offset: Int!) {
getComments(productId: $productId, limit: $limit, offset: $offset) {
success
comments {
_id
__typename
text
user {
_id
__typename
name
avatar
}
image
productId
createdAt
}
error {
message
}
}
}
```
I'm guessing the normalized cache would be something like this?
```
{
'comment:1': {
__typename: 'Comment',
text: 'nice comment',
...
},
...
ROOT_QUERY: {
getComments: {
__typename: 'CommentsResponse',
data: [
{ __ref: 'comment:1' },
...,
]
}
}
}
```
Having a query like above, the important part of the query is in the comments array returned by the query. success and error are only to check if the query was successful or not. I would like to know how the cache would look like for such a query. because I am having trouble in pagination and updating the cache. in this case, I would want to update the comments array rather than the full data object.
for example, Here I am trying to update the cache in the subscription. but I am having trouble updating the cache. can someone help me, please?
```
const { loading, data, subscribeToMore } = useGetCommentsQuery({
variables: { productId, offset: 0, limit: LIMIT },
notifyOnNetworkStatusChange: true,
});
useEffect(() => {
subscribeToMore({
document: CommentDocument,
variables: { productId },
updateQuery: (prev, { subscriptionData }) => {
if (!subscriptionData.data) return prev;
const newComment = subscriptionData.data.comment;
return {
...prev,
getComments: [...prev.getComments.comments, newComment],
};
},
});
}, [componentId, subscribeToMore]);
```
Contributor guide
Research direction
The issue names no repository files or tests. Start at the useGetCommentsQuery and subscribeToMore updateQuery entry points, inspect the getComments response shape and normalized-cache behavior, and define done as a reproducible pagination or subscription update that changes comments without discarding success or error.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- graphql, react, typescript
- Domain
- api, frontend
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 20/100