5 Ways To Handle Rest API Request In React Using CRUD Functions

Handling REST API requests in a React application typically involves using CRUD (Create, Read, Update, Delete) operations. Here are five common ways to handle REST API requests in React using CRUD functions.

Fetch API with useState and useEffect (Vanilla JavaScript)

Use the built-in Fetch API to make HTTP requests. Combine it with React's useState and useEffect hooks to manage the component state and handle asynchronous operations.

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

const MyComponent = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch('https://api.example.com/data');
        const result = await response.json();
        setData(result);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, []); // Empty dependency array means the effect runs once after the initial render

  return (
    <div>
      {data.map(item => (
        <p key={item.id}>{item.name}</p>
      ))}
    </div>
  );
};

export default MyComponent;

Axios Library

Use a popular HTTP client library like Axios for a cleaner syntax and additional features, such as interceptors for request/response handling and automatic JSON parsing.

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const MyComponent = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get('https://api.example.com/data');
        setData(response.data);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, []);

  return (
    <div>
      {data.map(item => (
        <p key={item.id}>{item.name}</p>
      ))}
    </div>
  );
};

export default MyComponent;

CRUD Operations with Axios

Extend the use of Axios to handle CRUD operations (Create, Read, Update, Delete).

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const MyComponent = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get('https://api.example.com/data');
        setData(response.data);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, []);

  const handleDelete = async (id) => {
    try {
      await axios.delete(`https://api.example.com/data/${id}`);
      // Update state or trigger a re-fetch as needed
    } catch (error) {
      console.error('Error deleting item:', error);
    }
  };

  // Similar functions for create, update

  return (
    <div>
      {data.map(item => (
        <div key={item.id}>
          <p>{item.name}</p>
          <button onClick={() => handleDelete(item.id)}>Delete</button>
        </div>
      ))}
    </div>
  );
};

export default MyComponent;

React Query Library

Use a dedicated data fetching library like React Query for managing the state of your data and handling complex scenarios like caching, invalidation, and background refetching.

import React from 'react';
import { useQuery } from 'react-query';

const MyComponent = () => {
  const { data, isLoading, isError } = useQuery('data', async () => {
    const response = await fetch('https://api.example.com/data');
    return response.json();
  });

  if (isLoading) return <p>Loading...</p>;
  if (isError) return <p>Error fetching data</p>;

  return (
    <div>
      {data.map(item => (
        <p key={item.id}>{item.name}</p>
      ))}
    </div>
  );
};

export default MyComponent;

Redux or Context API

For more advanced state management across components, you can use Redux or the Context API along with a middleware like Thunk to handle asynchronous actions.

// Example using Redux with Thunk middleware
// (Assuming you have set up your Redux store and actions)

import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { fetchData, deleteItem } from '../redux/actions/dataActions';

const MyComponent = () => {
  const dispatch = useDispatch();
  const data = useSelector(state => state.data);

  useEffect(() => {
    dispatch(fetchData());
  }, [dispatch]);

  const handleDelete = (id) => {
    dispatch(deleteItem(id));
  };

  return (
    <div>
      {data.map(item => (
        <div key={item.id}>
          <p>{item.name}</p>
          <button onClick={() => handleDelete(item.id)}>Delete</button>
        </div>
      ))}
    </div>
  );
};

export default MyComponent;

Choose the approach that best fits your project's requirements and complexity. For simple cases, the first two methods may be sufficient, while more complex applications may benefit from using libraries like Axios, React Query, or state management solutions like Redux.


Similar Articles