Using Mutation to Create and Invalidate Queries
Detail how to create, update, or delete server-side data using React Query's useMutation hook and then automatically invalidate queries to refresh the UI with the updated data.
import { useMutation, useQueryClient } from 'react-query';
const useCreateItem = () => {
const queryClient = useQueryClient();
return useMutation(createItem, {
onSuccess: () => {
// Invalidate and refetch
queryClient.invalidateQueries('items');
},
});
};
async function createItem(newItem) {
// Here you would make a request to your API to create an item
// For demonstration, this is mocked as a resolved promise
return Promise.resolve({ data: newItem });
}
This code defines a custom hook `useCreateItem` that uses `useMutation` to perform a mutation operation to create an item. After the item is successfully created, it automatically invalidates and refetches the queries related to 'items' using `invalidateQueries` to refresh the UI with updated data.
import { useMutation, useQueryClient } from 'react-query';
const useUpdateItem = () => {
const queryClient = useQueryClient();
return useMutation(updateItem, {
onSuccess: () => {
// Invalidate and refetch
queryClient.invalidateQueries('items');
},
});
};
async function updateItem(updatedItem) {
// Here you would make a request to your API to update an item
// For demonstration, this is mocked as a resolved promise
return Promise.resolve({ data: updatedItem });
}
This snippet demonstrates how to use `useMutation` to update server-side data. After updating the data with `updateItem`, the related queries are invalidated and refetched to ensure the UI reflects the most up-to-date data.
import { useMutation, useQueryClient } from 'react-query';
const useDeleteItem = () => {
const queryClient = useQueryClient();
return useMutation(deleteItem, {
onSuccess: () => {
// Invalidate and refetch
queryClient.invalidateQueries('items');
},
});
};
async function deleteItem(itemId) {
// Here you would make a request to your API to delete an item
// For demonstration, this is mocked as a resolved promise
return Promise.resolve({ id: itemId });
}
This code creates a hook `useDeleteItem` for deleting an item through a mutation operation. Upon successful deletion, it calls `invalidateQueries` to automatically refresh the list of items by invalidating and refetching the 'items' queries.