import axios from 'axios' import { useOptimisticMutation } from "./useOptimisticMutation.ts" type Response = boolean type Error = unknown type MutationVariables = {itemId: string} type Items = {id: string; name: string}[] type Likes = {itemId: string}[] type History = {type: string}[] function Component({items}: {items:Items}) { // Some local state for our example const [history, setHistory] = useState() // Mutation to delete an item and optimistically update data in three locations const {mutate: deleteItem} = useOptimisticMutation< Response, Error, MutationVariables, // Data types for our optimistic handlers [ Items | undefined, Likes | undefined, History ] >({ mutationFn: async (variables) => { return axios.post('/api/items/add', variables).then((res) => res.data) }, // This is where the magic happens optimistic: (variables) => { return [ // Remove from items { // The React Query key to find the cached data queryKey: ['items'], // Function to modify the cached data updater: (currentData) => { return currentData?.filter((item) => item.id !== variables.itemId) }, }, // Remove from likes { queryKey: ['likes'], updater: (currentData) => { return currentData?.filter((item) => item.itemId !== variables.itemId) }, }, // Update some local state by specifying `getData` and `setData` // Useful to handle with this hook so it gets rolled back on error { getData: () => history, setData: (data) => setHistory(data), updater: (currentData) => { return [...(currentData || []), {type: 'delete'}] }, }, ] }, }) return (