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) => {
    try {
      const response = await, requestData);
    } catch (err) {
  }, [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('');

  const handleSubmit = async (event) => {
    const formData = new FormData(;
    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>
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, 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) => {
    try {
      const response = await fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      const json = await response.json();
    } catch (err) {

  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.


Top comments (0)