Blog>
Snippets

Deleting Data Using TanStack Router

Explain the process of deleting data, demonstrating the setup of a 'delete' request route with TanStack Router and highlighting best practices for confirmation and error handling.
import { Router } from '@tanstack/router';

// Define your router
const router = new Router();

// Define a route for the delete operation
router.addRoute({
  path: '/delete/:id',
  async resolve({ params }) {
    // Confirm before deleting
    if (!confirm('Are you sure you want to delete?')) return;

    try {
      // Perform the delete operation, e.g., calling your API
      await deleteData(params.id);
      alert('Data deleted successfully.');
      // Redirect or update the UI as necessary
    } catch (error) {
      console.error('Failed to delete:', error);
      alert('Failed to delete data.');
    }
  }
});

// Function to call your API for deleting data
async function deleteData(id) {
  // Assuming a REST API
  const response = await fetch(`/api/data/${id}`, { method: 'DELETE' });
  if (!response.ok) throw new Error('Delete failed');
  return response.json();
}
This code snippet defines a route for deleting data using the TanStack Router. It listens for a path that includes an ID for the data to be deleted. Before performing the operation, it confirms with the user. If confirmed, it attempts to delete data by calling a fictional deleteData function, which you would replace with your actual data deletion logic, typically involving API communication. It handles success by indicating to the user that the operation was successful or catches and logs any errors that occur, providing user feedback on failure.