Blog>
Snippets

Using `useMutation` with TypeScript for Data Updates

Provide an example of using the `useMutation` hook with TypeScript to update data on the server and type-check the response and variables.
import { useMutation } from 'react-query';
import axios from 'axios';
import { QueryClient } from 'react-query';

// Define your data types
interface UserData {
  id: number;
  name: string;
}

// Example API function for updating user name
const updateUserName = async (userId: number, newName: string): Promise<UserData> => {
  const response = await axios.patch(`/users/${userId}`, { name: newName });
  return response.data;
};

const queryClient = new QueryClient();

export const useUpdateUserName = () => {
  return useMutation<UserData, Error, { userId: number; newName: string }>(({ userId, newName }) => updateUserName(userId, newName), {
    onSuccess: () => {
      // Invalidate and refetch
      queryClient.invalidateQueries('users');
    },
  });
};
This code snippet demonstrates how to use the `useMutation` hook from react-query with TypeScript. It includes a function `updateUserName` that takes a user ID and a new name, then makes a PATCH request to update the user's name. The `useUpdateUserName` hook is a wrapper around `useMutation`, allowing components to trigger updates. It specifies both the types for the mutation's variables and response using TypeScript for type-safety. Upon successful mutation, it invalidates the 'users' query to ensure data consistency.