Custom hook for an api call which can be a reusable component in reactJS

 Creating a custom hook for making API calls in React is a great way to encapsulate this functionality for reusability. Here's an example of how you can create a custom hook for API calls:

```jsx

import { useState, useEffect } from 'react';


function useApi(endpoint) {

  const [data, setData] = useState(null);

  const [loading, setLoading] = useState(true);

  const [error, setError] = useState(null);


  useEffect(() => {

    const fetchData = async () => {

      try {

        const response = await fetch(endpoint);

        if (!response.ok) {

          throw new Error('Network response was not ok');

        }

        const result = await response.json();

        setData(result);

      } catch (err) {

        setError(err);

      } finally {

        setLoading(false);

      }

    };


    fetchData();

  }, [endpoint]);


  return { data, loading, error };

}


export default useApi;

```


With this custom hook, you can make API calls in your React components like this:


```jsx

import React from 'react';

import useApi from './useApi';


function MyComponent() {

  const { data, loading, error } = useApi('https://api.example.com/data');


  if (loading) {

    return <div>Loading...</div>;

  }


  if (error) {

    return <div>Error: {error.message}</div>;

  }


  return (

    <div>

      {/* Render your data here */}

    </div>

  );

}


export default MyComponent;

```


You can use this `useApi` hook in multiple components throughout your application, making it a reusable component for API calls in React.

Comments

Popular Posts