0
0
ReactHow-ToBeginner · 3 min read

How to Make a Delete Request in React: Simple Guide

In React, you can make a delete request using the fetch API by setting the method to DELETE. Use fetch(url, { method: 'DELETE' }) inside an async function or event handler to remove data from a server.
📐

Syntax

The basic syntax for a delete request in React uses the fetch function with the method option set to DELETE. You provide the URL of the resource you want to delete.

  • url: The endpoint where the resource lives.
  • method: Set to DELETE to tell the server to remove the resource.
  • headers: Optional, for example to specify content type or authorization.
javascript
fetch('https://example.com/api/resource/1', {
  method: 'DELETE',
  headers: {
    'Content-Type': 'application/json'
  }
})
💻

Example

This example shows a React functional component with a button that deletes a user by ID when clicked. It uses async/await for clarity and handles the response to update the UI.

javascript
import React, { useState } from 'react';

export default function DeleteUser() {
  const [message, setMessage] = useState('');

  async function handleDelete() {
    try {
      const response = await fetch('https://jsonplaceholder.typicode.com/users/1', {
        method: 'DELETE'
      });
      if (response.ok) {
        setMessage('User deleted successfully');
      } else {
        setMessage('Failed to delete user');
      }
    } catch (error) {
      setMessage('Error: ' + error.message);
    }
  }

  return (
    <div>
      <button onClick={handleDelete}>Delete User</button>
      <p>{message}</p>
    </div>
  );
}
Output
User deleted successfully (after clicking the button)
⚠️

Common Pitfalls

  • Not handling the response: Always check if the response is ok to confirm deletion succeeded.
  • Forgetting to set method: The default fetch method is GET, so you must specify DELETE.
  • Ignoring async/await: Without waiting for the response, you might update UI too early.
  • Not catching errors: Network errors or server issues should be caught to avoid app crashes.
javascript
/* Wrong way: missing method and no error handling */
fetch('https://example.com/api/resource/1');

/* Right way: method set and error handled */
async function deleteResource() {
  try {
    const res = await fetch('https://example.com/api/resource/1', { method: 'DELETE' });
    if (!res.ok) throw new Error('Delete failed');
    console.log('Deleted');
  } catch (e) {
    console.error(e);
  }
}
📊

Quick Reference

Remember these tips when making delete requests in React:

  • Use fetch with method: 'DELETE'.
  • Always check response.ok to confirm success.
  • Use async/await to handle asynchronous calls cleanly.
  • Catch errors to handle network or server problems gracefully.

Key Takeaways

Use fetch with method 'DELETE' to make delete requests in React.
Always check the response status to confirm deletion succeeded.
Handle asynchronous calls with async/await for clarity and correctness.
Catch errors to prevent app crashes and inform users.
Set headers if your API requires authentication or specific content types.