Skip to content

Instantly share code, notes, and snippets.

@mackankowski
Last active September 7, 2021 07:14
Show Gist options
  • Save mackankowski/444ae46f1bfe497853ca684bb1a1db2d to your computer and use it in GitHub Desktop.
Save mackankowski/444ae46f1bfe497853ca684bb1a1db2d to your computer and use it in GitHub Desktop.
Network layer in React - using axios
import { useCallback, useContext } from "react";
import axios, { AxiosError, AxiosResponse } from "axios";
import { UserContext } from "modules/AuthManager/userContext";
export const useFetch = () => {
const { removeToken, token } = useContext(UserContext);
const getResponse = useCallback(
(
method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE",
url: string,
data?: {},
headers?: {}
) => {
let response: any;
const authHeader = {
Authorization: token,
};
switch (method) {
case "GET":
response = axios.get(url, {
headers: { ...authHeader, ...headers },
});
break;
case "POST":
response = axios.post(url, data, {
headers: { ...authHeader, ...headers },
});
break;
case "PUT":
response = axios.put(url, data, {
headers: { ...authHeader, ...headers },
});
break;
case "PATCH":
response = axios.patch(url, data, {
headers: { ...authHeader, ...headers },
});
break;
case "DELETE":
response = axios.delete(url, {
headers: { ...authHeader, ...headers },
});
break;
}
return response
.then(({ data }: AxiosResponse<any>) => {
return data;
})
.catch((e: AxiosError) => {
const { response } = e;
if (response?.status === 401) {
removeToken();
}
throw new Error(e.message);
});
},
[removeToken]
);
return getResponse;
};
import Cookies from "js-cookie";
export function getCookie() {
return Cookies.get("token");
}
export function setCookie(token: string) {
return Cookies.set("token", token);
}
export function removeCookie() {
return Cookies.remove("token");
}
...
const postAddUser = useFetch();
try {
await postAdd("POST", "endpoint/path", { someProperty: toSend });
} catch (e) {
console.error("Oh no!")
}
...
export interface UserContextInterface {
token?: string;
setToken: (token: any) => void;
removeToken: () => void;
}
import React, {
createContext,
ReactNode,
useCallback,
useMemo,
useState
} from "react";
import { getCookie, removeCookie, setCookie } from "./sessionHelper";
import { UserContextInterface } from "./types";
export const initialContextState = {
token: getCookie(),
setToken: (token: any) => {},
removeToken: () => {},
};
const UserContext = createContext<UserContextInterface>(initialContextState);
const UserContextProvider = UserContext.Provider;
interface Props {
children: ReactNode;
}
function UserProvider({ children }: Props) {
const tokenFromCookie = getCookie();
const [token, tokenSetter] = useState(tokenFromCookie);
const setToken = useCallback((token) => {
tokenSetter(token);
setCookie(token);
}, []);
const removeToken = useCallback(() => {
tokenSetter("");
removeCookie();
}, []);
const value = useMemo(
() => ({
token,
setToken,
removeToken,
}),
[removeToken, setToken, token]
);
return <UserContextProvider value={value}>{children}</UserContextProvider>;
}
UserProvider.displayName = "UserProvider";
export { UserProvider, UserContext };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment