React Hooks and POST method. All you need is a handler that triggers post method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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
1 2 3 4 5 6 7 | 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 like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.