Blog>
Snippets

Performing a Create Operation with TanStack Router

Showcase how to implement a 'create' operation using TanStack Router, focusing on the configuration of a post request to add new data to a server.
import { useMutation } from '@tanstack/react-query';
Import useMutation hook from TanStack React Query for performing the 'create' operation.
const createItem = async (newItem) => {
  const response = await fetch('/api/items', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(newItem),
  });
  if (!response.ok) {
    throw new Error('Error creating item');
  }
  return response.json();
};
Define an asynchronous function to perform the POST request, sending the new item data to the server and expecting a JSON response.
const { mutate: createNewItem, isLoading, error } = useMutation(newItem => createItem(newItem), {
  onSuccess: () => {
    // Handle success scenario, like showing a success message or refetching data
  },
  onError: (error) => {
    // Handle error scenario
  }
});
Use the useMutation hook to create a new item. Pass the createItem function as the mutation function. Use onSuccess and onError to handle success and failure scenarios respectively.
const handleSubmit = (itemData) => {
  createNewItem(itemData);
};
Define a function to handle form submission or any action that triggers the create operation, invoking the createNewItem mutation function with the item data.