I’m working with the Apollo local cache and it contains a list of comments. Every item has a liked property and I’d like to change the liked property on the user action. To achieve the fastest client UI update I wanted to use the optimisticResponse however, I still can’t find any possibility to do it so I’m wondering is it possible at all or is the OptimisticResponse works only in the case of simple use cases like addItem|deleteItem
?
Probably the main problem in my case is that I have the getCommets query and the likeComment dedicated mutation. Here are the detailed code examples:
A single Comment item schema:
{
"__typename": "Comment",
"contentOwner": true,
"id": "61b219358393f922246e5c5d",
"text": "Some comment text",
"liked": true,
}
To like a comment I have an appropriate mutation:
export const LIKE_COMMENT = gql`
mutation LikeComment($status: Boolean!, $commentId: String!) {
likeComment(status: $status, commentId: $commentId)
}
`;
After the mutation execution, I update the local cache to reflect the changes in the Client UI and use the optimisticResponse feature to update the comment like Icon immediately after the user interaction but it didn’t work somehow so I’m wondering if I did everything correctly, or is it just doesn’t work because of the difference between likeComment mutatuin and comments query?
const data = props.data; // a comment object from the parent HOC
const [
likeComment,
{ loading: likeCommentLoading, error: likeCommentError },
] = useMutation(LIKE_COMMENT, {
variables: {
status: !data.liked,
commentId: data.id,
},
optimisticResponse: {
comments: { // is my query name to get all the comments
id: data.id,
__typename: "Comment",
likeComment: !data.liked,
},
},
update(
cache,
{
data: {
// likeComment
},
}
) {
const ident = cache.identify(data);
cache.writeFragment({
id: ident,
fragment: gql`
fragment LikeCommentUpdate on Comment {
liked
}
`,
data: {
liked: !data.liked,
},
});
},
});
P.S. Not sure if it’s important but here is my getComments query. Just to be sure that the field comments in the optimisticResponse configuration object is correct
export const GET_COMMENTS_QUERY = gql`
${BASE_AUTHOR_FIELDS}
${EXTENDED_COMMENT_FIELDS}
${BASE_PAGINATION_FIELDS}
${BASE_REPORT_FIELDS}
query comments(
$before: String
$first: Int
$after: String
$threadId: String!
$communityId: String!
$parentId: String
) {
comments(...)
}
Many thanks for any help
Kind regards!