Created
June 23, 2020 22:00
-
-
Save Solijons/8d6942632d795cfe5fae02a7824f1fa4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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