React Hooks and POST method

Fabio Russo picture Fabio Russo · Apr 1, 2019 · Viewed 9.1k times · Source

I need to understand how can I setup a custom hook in React, for a POST method.

If I need to POST some data after a click, but I can't use the custom hook in an event handler, how can I do It?

I made a custom Hook with all the fetch logic and the relative reducers... but I dunno how to use It in a click, without breaking the rules.

Thanks.

Answer

Shubham Khatri picture Shubham Khatri · Apr 1, 2019

All you need is a handler that triggers post method

const useFetchData = ({url, headers, payload}) => {
    const [res, setRes] = useState({data: null, error: null, isLoading: false});
    const [error, setError]
    // You POST method here
    const callAPI = useCallback(() => {
         setRes(prevState => ({...prevState, isLoading: true}));
         axios.post(url, headers, payload).then(res => {
            setRes({data: res.data, isLoading: false, error: null});
         }).catch((error) => {
            setRes({data: null, isLoading: false, error});
         })
    }, [url, headers, payload])
    return [res, callAPI];
}

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

const MyFunc = () => {
   const [res, apiMethod] = useFetchData({url: 'some url here', headers: {ContentType: 'text/plain'}, payload: {}});

   return (
      <button onClick={() => {apiMethod()}} type="button">Submit data</button>
   )
}

You could event have payload defined in the component state and pass it on to the useFetchData as argument.