Skip to content
Snippets Groups Projects

Resolve "Discuss and implement proper API methods."

Merged Maciej Lenartowicz requested to merge 6-api-hooks into dev
Files
2
+ 8
5
@@ -12,6 +12,8 @@ import {
API_STATE, API_ACTIONS, API_METHODS, TIMEOUT, HEADERS, getErrorMessage,
} from "./utils";
const DATA_METHODS = ["POST", "PATCH", "PUT"];
function createAPIHook(method) {
return (url, contentType) => {
const [state, dispatch] = useReducer(APIReducer, {
@@ -27,13 +29,13 @@ function createAPIHook(method) {
dispatch({ type: API_ACTIONS.INIT });
try {
const req = API_METHODS[method];
const request = API_METHODS[method];
const config = { timeout: TIMEOUT, headers };
let result;
if (["POST", "PATCH"].includes(method)) {
result = await req(url, data, config);
if (DATA_METHODS.includes(method)) {
result = await request(url, data, config);
} else {
result = await req(url, config);
result = await request(url, config);
}
dispatch({ type: API_ACTIONS.SUCCESS, payload: result.data });
} catch (error) {
@@ -76,8 +78,9 @@ function APIReducer(state, action) {
const useAPIGet = createAPIHook("GET");
const useAPIPost = createAPIHook("POST");
const useAPIPatch = createAPIHook("PATCH");
const useAPIPut = createAPIHook("PUT");
const useAPIDelete = createAPIHook("DELETE");
export {
useAPIGet, useAPIPost, useAPIPatch, useAPIDelete,
useAPIGet, useAPIPost, useAPIPatch, useAPIPut, useAPIDelete,
};