Skip to content

Instantly share code, notes, and snippets.

@rhogeranacleto
Created August 17, 2021 16:56
Show Gist options
  • Save rhogeranacleto/7b1ec242a1be38cec1191331c9ce6eab to your computer and use it in GitHub Desktop.
Save rhogeranacleto/7b1ec242a1be38cec1191331c9ce6eab to your computer and use it in GitHub Desktop.
use axios hook
import Axios from 'axios';
import { Dispatch, Reducer, useCallback, useReducer } from 'react';
interface IAxiosData<T> {
data?: T;
loading: boolean;
error?: Error;
}
enum UseFatchActions {
set = 'SET',
start = 'START',
finish = 'FINISH',
fail = 'FAIL',
}
interface IAction<T> {
type: UseFatchActions;
data?: T;
error?: Error;
}
const fetchReducer = <T>(
state: IAxiosData<T>,
action: IAction<T>,
): IAxiosData<T> => {
switch (action.type) {
case UseFatchActions.set: {
return { ...state, data: action.data };
}
case UseFatchActions.start:
return { ...state, loading: true };
case UseFatchActions.finish:
return { ...state, loading: false };
case UseFatchActions.fail:
return { ...state, error: action.error };
default:
return state;
}
};
type UseAxiosResult<T> = IAxiosData<T> & {
refresh: (config: Parameters<typeof Axios>) => Promise<void>;
dispatch: Dispatch<IAction<T>>;
};
export const useAxios = <T>(): UseAxiosResult<T> => {
const [state, dispatch] = useReducer<Reducer<IAxiosData<T>, IAction<T>>>(
fetchReducer,
{ loading: false },
);
const refresh = useCallback(async (config: Parameters<typeof Axios>) => {
dispatch({ type: UseFatchActions.start });
try {
const { data } = await Axios(...config);
dispatch({ type: UseFatchActions.set, data });
} catch (e) {
dispatch({ type: UseFatchActions.fail, error: e });
}
dispatch({ type: UseFatchActions.finish });
}, []);
return { ...state, refresh, dispatch };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment