I am currently creating a simple application where an user can login and after login he receives a token.
I am using React context to store that token, each subsequent request should be done with the token.
To not send the token on each request I want to include it in the intercptor, so I ended up with something like this:
HttpService:
import axios, { AxiosRequestConfig } from 'axios'
import { useToken } from '../context/AccessTokenContext'
const axiosConfig: AxiosRequestConfig = {
baseURL: 'localhost:3000',
}
const http = axios.create(axiosConfig)
http.interceptors.request.use(function (config) {
const { token } = useToken()
if (config.url != '/users/login') {
if (config?.headers?.common && token) {
config.headers.common['Authorization'] = `Bearer ${token}`
}
}
return config
})
export default http
AuthContext
import React, { createContext, ReactNode, useContext, useState } from 'react'
export const AccessTokenContext = createContext<{
token: string | null
setToken: (base: string | null) => void
}>({ token: null, setToken: () => null })
interface IAccessTokenProvider {
children: ReactNode
}
export const AccessTokenProvider = (props: IAccessTokenProvider) => {
const [token, setToken] = useState<string | null>(null)
return (
<AccessTokenContext.Provider value={{ token, setToken }}>
{props.children}
</AccessTokenContext.Provider>
)
}
export const useToken = () => {
return useContext(AccessTokenContext)
}
The thing is after login I do another request and the token was not set yet. Is there any easier way to do this? I tried to also store it just in memory without react, but with that I cant automaticly update the route, because it reacts to the token change.