From 8b42c0b004aff9c494355e7e61ab47b0b49b2509 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Thu, 2 Jun 2022 01:29:37 +0200 Subject: [PATCH] Create useAxios hook --- hooks/useAxios.ts | 18 ++++++++++++++++++ pages/_app.tsx | 16 ++++++---------- 2 files changed, 24 insertions(+), 10 deletions(-) create mode 100644 hooks/useAxios.ts diff --git a/hooks/useAxios.ts b/hooks/useAxios.ts new file mode 100644 index 0000000..fdc0321 --- /dev/null +++ b/hooks/useAxios.ts @@ -0,0 +1,18 @@ +import {default as axios} from "axios"; +import { useContext, useMemo } from "react"; +import { LoginContext } from "../contexts/login"; +import { FestaLoginData } from "../types/user"; +import { useDefinedContext } from "../utils/definedContext"; + +export function useAxios(data?: FestaLoginData | null) { + const loginContext = useContext(LoginContext) + + const headers: {[key: string]: string} = {} + + let login = data || loginContext?.[0] + if(login) { + headers["Authorization"] = `Bearer ${login.token}` + } + + return useMemo(() => axios.create({headers}), [login]) +} diff --git a/pages/_app.tsx b/pages/_app.tsx index 0e59f3e..72ede84 100644 --- a/pages/_app.tsx +++ b/pages/_app.tsx @@ -9,25 +9,21 @@ import { StaticImageData } from 'next/image' import { appWithTranslation } from 'next-i18next' import { FestaLoginData } from '../types/user' import {useStoredLogin} from "../hooks/useStoredLogin" -import { Fetcher, SWRConfig } from 'swr' -import axios, { AxiosRequestConfig } from 'axios' +import { SWRConfig } from 'swr' +import { AxiosRequestConfig } from 'axios' +import { useAxios } from '../hooks/useAxios' const App = ({ Component, pageProps }: AppProps): JSX.Element => { const [postcard, setPostcard] = useState(defaultPostcard) - const [login, setLogin] = useState(null) useStoredLogin(setLogin) - const axiosConfig = { - headers: { - "Authorization": login ? `Bearer ${login.token}` : "", - } - } + const axios = useAxios(login) const swrConfig = { - fetcher: async (resource: string, localAxiosConfig: AxiosRequestConfig) => { - const response = await axios.get(resource, {...axiosConfig, ...localAxiosConfig}) + fetcher: async (resource: string, init: AxiosRequestConfig) => { + const response = await axios.get(resource, init) // To test loading uncomment the following line: // await new Promise(res => setTimeout(res, 100000)) return response.data