GraphQL
Beginner
1 min read
Optimistic UI and Cache Updates with Apollo Client
Example
// Apollo Client mutation with optimistic UI
import { useMutation, gql } from '@apollo/client';
const LIKE_POST = gql`
mutation LikePost($id: ID!) {
likePost(id: $id) {
id
likeCount
likedByMe
}
}
`;
function LikeButton({ post }) {
const [likePost] = useMutation(LIKE_POST, {
// Optimistic response — shown immediately
optimisticResponse: {
likePost: {
__typename: 'Post',
id: post.id,
likeCount: post.likeCount + 1,
likedByMe: true,
},
},
// Manual cache update for lists not auto-updated
update(cache, { data: { likePost } }) {
cache.modify({
id: cache.identify(likePost),
fields: {
likeCount: () => likePost.likeCount,
likedByMe: () => likePost.likedByMe,
},
});
},
});
return (
<button onClick={() => likePost({ variables: { id: post.id } })}>
{post.likedByMe ? '♥' : '♡'} {post.likeCount}
</button>
);
}
Related Resources
GraphQL Reference
Complete tag & property list
GraphQL How-To Guides
Step-by-step practical guides
GraphQL Exercises
Practice what you've learned
More in GraphQL