Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
// 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> ); }
Result
Open