Skip to content

Instantly share code, notes, and snippets.

@Solijons
Created June 23, 2020 22:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Solijons/8d6942632d795cfe5fae02a7824f1fa4 to your computer and use it in GitHub Desktop.
Save Solijons/8d6942632d795cfe5fae02a7824f1fa4 to your computer and use it in GitHub Desktop.
import { useCallback, useReducer } from 'react';
const initialState = {
error: null,
extra: null,
data: null,
identifier: null,
loading: false,
};
const httpReducer = (curHttpState: any, action: any) => {
switch (action.type) {
case 'SEND':
return {
loading: true,
error: null,
data: null,
extra: null,
identifier: action.identifier
};
case 'RESPONSE':
return {
...curHttpState,
loading: false,
data: action.responseData,
extra: action.extra
};
case 'ERROR':
return { loading: false, error: action.errorMessage };
case 'CLEAR':
return initialState;
default:
throw new Error('Should not be reached!');
}
};
const useHttpReactHook = () => {
const [httpState, dispatchHttp] = useReducer(httpReducer, initialState);
const clear = useCallback(() => dispatchHttp({ type: 'CLEAR' }), []);
const sendRequest = useCallback(
(url, method, body, reqExtra, reqIdentifer) => {
dispatchHttp({ type: 'SEND', identifier: reqIdentifer });
fetch(url, {
method,
body,
headers: {
'Content-Type': 'application/json'
}
})
.then((response) => {
return response.json();
})
.then((responseData) => {
dispatchHttp({
type: 'RESPONSE',
responseData,
extra: reqExtra
});
})
.catch((error) => {
dispatchHttp({
type: 'ERROR',
errorMessage: 'Something went wrong!'
});
});
},
[]
);
return {
clear,
data: httpState.data,
error: httpState.error,
isLoading: httpState.loading,
reqExtra: httpState.extra,
reqIdentifer: httpState.identifier,
sendRequest,
};
};
export default useHttpReactHook;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment