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
3
+ 8
20
@@ -6,26 +6,13 @@
*/
import { useReducer, useCallback } from "react";
import axios from "axios";
import { ForisURLs } from "forisUrls";
import {
API_ACTIONS, TIMEOUT, HEADERS, getErrorMessage,
API_STATE, API_ACTIONS, API_METHODS, TIMEOUT, HEADERS, getErrorMessage,
} from "./utils";
const API_STATE = {
INIT: "init",
SENDING: "sending",
SUCCESS: "success",
ERROR: "error",
};
const API_METHODS = {
GET: axios.get,
POST: axios.post,
PATCH: axios.patch,
DELETE: axios.delete,
};
const DATA_METHODS = ["POST", "PATCH", "PUT"];
function createAPIHook(method) {
return (url, contentType) => {
@@ -42,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) {
@@ -91,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, API_STATE,
useAPIGet, useAPIPost, useAPIPatch, useAPIPut, useAPIDelete,
};