Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

197
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!