Performing Mutations with useMutation Hook
Provide an example of using the `useMutation` hook from React Query to perform mutations on a GraphQL API, including optimistic updates for a seamless user experience.
import { useMutation, useQueryClient } from 'react-query';
import { gql } from 'apollo-boost';
Import necessary hooks from react-query and gql from apollo-boost.
const CREATE_POST_MUTATION = gql`
mutation CreatePost($title: String!, $content: String!) {
createPost(input: { title: $title, content: $content }) {
id
title
content
}
}
`;
Define the GraphQL mutation for creating a post.
function useCreatePost() {
const queryClient = useQueryClient();
return useMutation(
[CREATE_POST_MUTATION],
variables =>
fetch('/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: CREATE_POST_MUTATION, variables }),
}).then(response => response.json()),
{
// Optimistically update to the new value
onMutate: async newPost => {
await queryClient.cancelQueries('posts');
const previousPosts = queryClient.getQueryData('posts');
queryClient.setQueryData('posts', old => [...old, newPost]);
return { previousPosts };
},
// If the mutation fails, use the context returned from onMutate to roll back
onError: (err, newPost, context) => {
queryClient.setQueryData('posts', context.previousPosts);
},
// Always refetch after error or success:
onSettled: () => {
queryClient.invalidateQueries('posts');
},
}
);
}
Create a custom hook using the useMutation hook to handle the create post mutation with optimistic updates for seamless UI experience.