Access function argument inside function react hooks

Viewed 123

I am writing a custom react hook for fetching data from an endpoint. This is what the function looks like

import { useState } from "react";

const useHttp = async (endpoint, method, data) => {

    const [loading, setLoading] = useState(false)
    const [fetchedData, setfetchedData] = useState(null)

    setfetchedData(await fetch.method(endpoint));
    return [isLoading, fetchedData]
}

export default  useHttp;

As you can see, I want to do a fetch request to whatever method is passed on to the useHttp hook. Please someone point me how to do it?

3 Answers

Use useEffect hook to make the HTTP request.

fetch function takes an optional second argument which is an object specifying various options for the HTTP request and one of the options is a method option. Use this method option to specify the request method.

import { useState, useEffect } from "react";

const useHttp = async (endpoint, method, data) => {

    const [loading, setLoading] = useState(false);
    const [fetchedData, setfetchedData] = useState(null);

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

        fetch(endpoint, { method })
          .then(res => res.json())
          .then(data => {
             setLoading(false);
             setfetchedData(data);
          }) 
          .catch(err => {
              setLoading(false);
              console.log(err.message);
          });

    }, []);


    return [isLoading, fetchedData];
}

For details on how to specify options for fetch function and different options that can be specified, see using fetch

If you want to use async-await syntax, you can write useEffect hook as:

useEffect(() => {

    async function makeRequest() {
        setLoading(true);

        try {
            const response = await fetch(endpoint, { method });
            const data = await res.json();
            
            setLoading(false);
            setfetchedData(data);
        
        } catch (error) {
           setLoading(false);
           console.log(err.message);
        }
    }

    makeRequest();

}, []);

You cannot pass async functions to React Hooks. You have to useEffect

import { useState, useEffect } from "react";

const useHttp = (endpoint, method, options) => {
  const [isLoading, setLoading] = useState(false);
  const [fetchedData, setFetchedData] = useState(null);

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

    fetch(endpoint, { method, ...options })
      .then(data => data.json())
      .then((json) => {
        // do something with JSON data
        setFetchedData(json);
      })
      .catch((err) => {
        // do something with err
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);
  return [isLoading, fetchedData];
};

export default useHttp;

hi maybe this help you:

1- call function:

const useHttp = async (url,method,data)=>{
            var options = {
                method:method,
                headers: {
                    'Content-Type': 'application/json; charset=utf-8;'
                }
            };
            if(method==='POST' && data)
               options.body =  JSON.stringify(data);
            const response = await fetch(url, options);
            const rep = await response.json();
            console.log(rep);
            return rep;
};

in above code first create your request options and then send it by fetch to end point.

2- use it in compoent like below:

setLoading(true);
var rep = await useHttp(...)
setLoading(false);
Related