Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Hooks and POST method

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 don't know, how to use It in a click, without breaking the rules.

like image 477
Fabio Russo Avatar asked Apr 01 '19 14:04

Fabio Russo


People also ask

How do you use post in React?

Use Plain JavaScript to Make a POST Request in React In JavaScript, the traditional way to send any request to an API is using the XMLHttpRequest() interface. You can create an instance of this object and store it in the variable. Copy var req = new XMLHttpRequest(); req. open('POST', '/endpoint', true); req.

What is React Hooks used for?

Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don't work inside classes — they let you use React without classes. (We don't recommend rewriting your existing components overnight but you can start using Hooks in the new ones if you'd like.)

Is it better to use Hooks in React?

Hooks make React so much better because you have simpler code that implements similar functionalities faster and more effectively. You can also implement React state and lifecycle methods without writing classes.


1 Answers

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.

like image 146
Shubham Khatri Avatar answered Oct 06 '22 00:10

Shubham Khatri