DEV Community

Krishna Bhamare
Krishna Bhamare

Posted on

React | POST API call using custom hook😎.

Here's an example of a usePost hook that you can use to make a POST request in a React application:

Post Call Using Axios:

import { useState, useCallback } from 'react';
import axios from 'axios';

export default function usePost(url) {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);
  const [data, setData] = useState(null);

  const makeRequest = useCallback(async (requestData) => {
    setIsLoading(true);
    setError(null);
    try {
      const response = await axios.post(url, requestData);
      setData(response.data);
    } catch (err) {
      setError(err);
    }
    setIsLoading(false);
  }, [url]);

  return { makeRequest, data, isLoading, error };
}

Enter fullscreen mode Exit fullscreen mode

You can use this hook in your component like this:

import usePost from './usePost';

function MyComponent() {
  const { makeRequest, data, isLoading, error } = usePost('https://my-api.com/post-endpoint');

  const handleSubmit = async (event) => {
    event.preventDefault();
    const formData = new FormData(event.target);
    await makeRequest(formData);
  }

  if (error) {
    return <div>An error occurred: {error.message}</div>;
  }

  if (isLoading) {
    return <div>Loading...</div>;
  }

  return (
    <form onSubmit={handleSubmit}>
      {/* ... your form inputs ... */}
      <button type="submit">Submit</button>
    </form>
  );
}
Enter fullscreen mode Exit fullscreen mode
  • In the above example, when the form is submitted, the handleSubmit function is called. It prevents the default form submission behavior and gets the data from the form using FormData. Then, it calls makeRequest function, passing in the formData, which triggers the API call and sets the data, isLoading, and error state accordingly.

  • The makeRequest Function accepts the data to be sent to the API endpoint and it uses Axios library to make the API call.

  • usePost Hook expose makeRequest, data, isLoading, error state via the returned object. which can be used in the component to handle different scenarios like error, loading, and data display.

  • You can also pass the configuration options to axios if you want like headers, auth token, etc.

const config = {
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`
  }
};

const response = await axios.post(url, requestData,config);
Enter fullscreen mode Exit fullscreen mode

Post Call Using Fetch:

usePost hook that you can use to make a POST request using Fetch,

import { useState, useEffect } from 'react';

const usePost = (url) => {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);

  const postData = async (body) => {
    setLoading(true);
    try {
      const response = await fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      });
      const json = await response.json();
      setData(json);
    } catch (err) {
      setError(err);
    }
    setLoading(false);
  };

  return { postData, data, error, loading };
};

export default usePost;
Enter fullscreen mode Exit fullscreen mode

You can use these properties to control the behavior of your component while the request is being made and after the response is received.
Please note that the example above is a simple example of a hook and it does not account for error handling like input validation or retries or other possible edge cases.

Thanks...!!!

Top comments (2)

Collapse
 
sajjad_ahmad_aa33703dfe0c profile image
Sajjad Ahmad

your article is helpfull me , I appricate you keep it up dear

Collapse
 
krishna7852 profile image
Krishna Bhamare

Thanks