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.
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.
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.)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With