mirror of
https://github.com/Steffo99/festa.git
synced 2024-12-22 14:44:21 +00:00
Create useAxios hook
This commit is contained in:
parent
783121b140
commit
8b42c0b004
2 changed files with 24 additions and 10 deletions
18
hooks/useAxios.ts
Normal file
18
hooks/useAxios.ts
Normal 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])
|
||||
}
|
|
@ -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<string | StaticImageData>(defaultPostcard)
|
||||
|
||||
const [login, setLogin] = useState<FestaLoginData | null>(null)
|
||||
useStoredLogin(setLogin)
|
||||
|
||||
const axiosConfig = {
|
||||
headers: {
|
||||
"Authorization": login ? `Bearer ${login.token}` : "",
|
||||
}
|
||||
}
|
||||
const axios = useAxios(login)
|
||||
|
||||
const swrConfig = {
|
||||
fetcher: async (resource: string, localAxiosConfig: AxiosRequestConfig<any>) => {
|
||||
const response = await axios.get(resource, {...axiosConfig, ...localAxiosConfig})
|
||||
fetcher: async (resource: string, init: AxiosRequestConfig<any>) => {
|
||||
const response = await axios.get(resource, init)
|
||||
// To test loading uncomment the following line:
|
||||
// await new Promise(res => setTimeout(res, 100000))
|
||||
return response.data
|
||||
|
|
Loading…
Reference in a new issue