1

I was trying to create a custom Hooks for handling input HTTP request from any component by simply calling the useCustomHooks but its getting failed and error is

Can not use keyword 'await' outside an async function

All i made is a handler that triggers http request custom component method

import { useState } from 'react';
import axios from "axios";

const useHttpReqHandler = () => {
    const [result, setResult] = useState();

    const apiMethod = async ({url , data , method}) => {
        let options = {
            method,
            url,
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json;charset=UTF-8'
            },
            data
        };
        let response = await axios(options);
        const UpdatedData = await response.data;
        console.log(UpdatedData)
        setResult(UpdatedData);
    }

    return [result, apiMethod];
};

export default useHttpReqHandler;

Now i can use this hook in my code and on any event handler just call callAPI returned from the hook like this

const MyFunc = () => {
    const [apiResult, apiMethod] = useHttpReqHandler();


    const captchValidation = () => {
        const x = result.toString();;
        const y = inputValue.toString();;
        if ( x === y) {
            apiMethod({url: 'some url here', data: {"email": email}, method: 'post'});
             alert("success")
        }
        else {
             alert("fail")
        }

    }

Is is a correct approch ? as i am beginner in Reactjs

8
  • You're calling await inside useEffect, but useEffect is not async Commented Apr 21, 2020 at 15:01
  • Hi @HermitCrab is this a right approach? i made an edit to my post, but will run infinite times Commented Apr 21, 2020 at 15:09
  • There are many mistakes in your custom hook, I can work on it and post a working version if you want Commented Apr 21, 2020 at 15:13
  • Hi @HermitCrab if you can it will be useful thanks if you can do this for me as i have started react with from last 2 weeks only Commented Apr 21, 2020 at 15:25
  • Hi @HermitCrab if you can guide me it will so much helpful Commented Apr 21, 2020 at 15:44

2 Answers 2

4

Here is a working version:

useHttpReqHandler.jsx

import { useState } from 'react';
import axios from "axios";

const useHttpReqHandler = () => {
    const [apiResult, setApiResult] = useState();

    const apiMethod = async ({url , data , method}) => {
        let options = {
            method,
            url,
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json;charset=UTF-8'
            },
            data
        };
        let response = await axios(options);
        let responseOK = response && response.status === 200 && response.statusText === 'OK';
        if (responseOK) {
            const data = await response.data;
            console.log(data)
            setApiResult(data);
        }
    }

    return [apiResult, apiMethod];
};

export default useHttpReqHandler;

What's important here:

  • await is called inside an async function (apiMethod)

  • The result is stored in a local state (apiResult)

  • The function returns an array [apiResult, apiMethod]

How to use it:

const [apiResult, apiMethod] = useHttpReqHandler();
apiMethod({url: 'some url here', data: {"email": email}, method: 'post'});

Render the result:

return {apiResult};
Sign up to request clarification or add additional context in comments.

4 Comments

Hi @HermitCrab, I am not able to get how to use it? i just made an edit to the question can i use in this way ? please do look
useHttpReqHandler must return an array. First element is a state variable (apiResult) that will be updated after a successful axios call, second element is a function to call (apiMethod)
As i had made an edit in question is that the right approach?
Hi @HermitCrab how can I add sppiner in your code ? if you got a time please do add in your code
1

In my opinion, it is better to use .then with Axios. and try to create for each method different functions "Get/Post...", why because in the GET method you need to useEffect, but it can not be the same case in POST method. in GET method useHttpReqHandler.js

import { useEffect, useState } from "react";
import axios from "axios";

// GET DATA
const useHttpReqHandler = (url) => {
  const [httpData, setHttpData] = useState();

  useEffect(() => {
    axios
      .get(url)
      .then((axiosData) => {
        // Axios DATA object

        setHttpData(axiosData.data);
        // you can check what is in the object by console.log(axiosData);
        // also you can change the state, call functions...
      })
      .catch((error) => {
        console.log(error);
      });
  }, []);

  return httpData;
};
export default useHttpReqHandler;

in your main file

import useHttpReqHandler from "...."
const MyFunc = () => {
       const getData = useHttpReqHandler("URL");

   return (
      <div>
...
</div>
   )
}

I hope it helps

the same thing will be with POSt, PUT, DELETE ... you will create functions for each method that will handle the Http req

2 Comments

hi @Ahmed for post request how will i send post req parameter in this way ``` axios.post(url ,data)```
you can do it like this axios.post(https:api.com/${parameter},yourData);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.