Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

198
Visualizações
Access React Context data inside Axios Interceptor

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.

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda