Nice hook!
import { useState, useEffect } from 'react'; import axios from 'axios'; axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com'; const useAxios = ({ url, method, body = null, headers = null, config = {} }) => { ... const fetchData = () => { axios[method](url, JSON.parse(headers), JSON.parse(body), ...config) .then((res) => { setResponse(res.data); }) .catch((err) => { setError(err); }) .finally(() => { setloading(false); }); }; useEffect(() => { fetchData(); }, [method, url, body, headers, config]); return { response, error, loading }; }; export default useAxios;
In component:
// App component import { CancelToken } from 'axios'; const App = () => { const source = CancelToken.source() const { response, loading, error } = useAxios({ method: 'post', url: '/posts', headers: JSON.stringify({ accept: '*/*' }), config: { cancelToken: source.token, }, body: JSON.stringify({ userId: 1, id: 19392, title: 'title', body: 'Sample text', }), }); ... source.cancel('cancel request') }
Some comments have been hidden by the post's author - find out more
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Nice hook!
In component: