DEV Community

Discussion on: useAxios : A simple custom hook for calling APIs using axios

Collapse
 
jace profile image
Jace Chou • Edited

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;
Enter fullscreen mode Exit fullscreen mode

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')

}

Enter fullscreen mode Exit fullscreen mode

Some comments have been hidden by the post's author - find out more