Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

199
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda