1
Fork 0
mirror of https://github.com/Steffo99/festa.git synced 2024-12-22 22:54:22 +00:00

Create useAxios hook

This commit is contained in:
Steffo 2022-06-02 01:29:37 +02:00
parent 783121b140
commit 8b42c0b004
Signed by: steffo
GPG key ID: 6965406171929D01
2 changed files with 24 additions and 10 deletions

18
hooks/useAxios.ts Normal file
View file

@ -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])
}

View file

@ -9,25 +9,21 @@ import { StaticImageData } from 'next/image'
import { appWithTranslation } from 'next-i18next' import { appWithTranslation } from 'next-i18next'
import { FestaLoginData } from '../types/user' import { FestaLoginData } from '../types/user'
import {useStoredLogin} from "../hooks/useStoredLogin" import {useStoredLogin} from "../hooks/useStoredLogin"
import { Fetcher, SWRConfig } from 'swr' import { SWRConfig } from 'swr'
import axios, { AxiosRequestConfig } from 'axios' import { AxiosRequestConfig } from 'axios'
import { useAxios } from '../hooks/useAxios'
const App = ({ Component, pageProps }: AppProps): JSX.Element => { const App = ({ Component, pageProps }: AppProps): JSX.Element => {
const [postcard, setPostcard] = useState<string | StaticImageData>(defaultPostcard) const [postcard, setPostcard] = useState<string | StaticImageData>(defaultPostcard)
const [login, setLogin] = useState<FestaLoginData | null>(null) const [login, setLogin] = useState<FestaLoginData | null>(null)
useStoredLogin(setLogin) useStoredLogin(setLogin)
const axiosConfig = { const axios = useAxios(login)
headers: {
"Authorization": login ? `Bearer ${login.token}` : "",
}
}
const swrConfig = { const swrConfig = {
fetcher: async (resource: string, localAxiosConfig: AxiosRequestConfig<any>) => { fetcher: async (resource: string, init: AxiosRequestConfig<any>) => {
const response = await axios.get(resource, {...axiosConfig, ...localAxiosConfig}) const response = await axios.get(resource, init)
// To test loading uncomment the following line: // To test loading uncomment the following line:
// await new Promise(res => setTimeout(res, 100000)) // await new Promise(res => setTimeout(res, 100000))
return response.data return response.data