DEV Community

Luis Esteban Saravia M
Luis Esteban Saravia M

Posted on

3 2

Custom Hook to Manage Api Request

If you want to make API requests in a React functional component, you can use the useEffect hook to perform the request. However, this can quickly become repetitive and difficult to manage if you need to make multiple requests in your component.

To make this process easier, you can create a custom hook called useAPI that wraps the useEffect hook and provides a simple interface for making API requests. Here is an example of how you might create the useAPI hook:

import { useState, useEffect } from 'react';

function useAPI({method, url, body}) {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true);
    setError(null);

    fetch(url, {
      method,
      body: JSON.stringify(body),
      headers: {
        'Content-Type': 'application/json',
      },
    })
      .then(response => response.json())
      .then(data => setData(data))
      .catch(error => setError(error))
      .finally(() => setLoading(false));
  }, [method, url, body]);

  return { data, error, loading };
}

Enter fullscreen mode Exit fullscreen mode

In this example, the useAPI hook takes a method, url, and body parameter, and uses the useState and useEffect hooks to make an API request using the specified method and url. The body parameter is stringified and included in the request as the request body. The hook also tracks the loading state, data, and error state of the request, and returns them as an object.

To use the useAPI hook in a functional component, you can call the hook and destructure the returned object to access the data, error, and loading state. Here is an example of how you might use the useAPI hook in a functional component:

import React from 'react';
import { useAPI } from './useAPI';

function MyComponent() {
const {data, error, loading} = useAPI({
         method:'POST', 
         url: 'https://my-api.com/data', 
         body: {title: 'My Post'}
     });
...
}

Enter fullscreen mode Exit fullscreen mode

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)