0

I was trying to create a custom Hooks for handling input HTTP request from any component by simply calling the useHttpPOSTHandler and want to use .then with Axios but its getting failed and error is as i am new in react not able to debug this what i have tried

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

const useHttpPOSTHandler = ({url , data}) => {
    const [httpData, setHttpData] = useState();

    const apiMethod = useCallback( ({url , data}) => {
        axios
          .post(url , data)
          .then((response) => {
            console.log(response)
            console.log(response.data)
            setHttpData(response.data);
          })
          .catch((error) => {
            console.log(error);
          });
    }, [setHttpData])

    return [ httpData , apiMethod];
};

export default useHttpPOSTHandler;
Akhi21
  • 219
  • 4
  • 16

1 Answers1

1

The arguments to useHTTPPostHandler are expected to be an object with keys url and data instead you are passing them individually causing a syntax error, wrap them within {}

const getData = useHttpPOSTHandler(
     { url: 'url', data: { "password": userPassword, "username": userName }
});

EDIT: As per your update, you won't see the updated data as soon as you make an API call. It will reflect in the next render

import useHttpPOSTHandler from "...."
const MyFunc = () => {
    const [httpData, apiMethod] = useHttpPOSTHandlerdotthen()

    const handleSubmit = () => {
        apiMethod({url: 'url' , data: { "password": userPassword, "username": userName }})
    }

   if(httpData){
       console.log("entered in api method")
       console.log(httpData)
   }

   return (
      <div>
         ...
      </div>
   )
}
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • Hi @Shubham Khatri i just update the question is that logic right? i dont want to use useEfect – Akhi21 Apr 25 '20 at 16:40
  • updated the answer,your logic is almost correct barring the fact that the data is available on next render – Shubham Khatri Apr 25 '20 at 16:53
  • hi @Shubham Khatri can you tell how to route from one page to another in reactjs as i am beginner in it https://stackoverflow.com/questions/61431471/how-to-route-from-one-page-to-another-in-react-hooks – Akhi21 Apr 25 '20 at 19:37