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

142
Vistas
Is there a way to fetch data only when token Is available?

Good day all,

I have a little issue in my react code and I hope someone here would be able to help me fix it.

Basically I am fetching data from an endpoint (multiple) Am using axios and react query.

In my get request, I have security headers and one is Authorization. User is authorized by a token sent to session storage when he / she login.

I get the token from session storage and place it in my authorization header. My problem now is before the user login, the token === null and my get request runs before the user logins leaving it with an empty token.

When the user finally logins, no data is fetched because what is in the authorization header is null but when I refresh the page, the data is fetched because at that time the token was already delivered and not = null.

I don't know if you fully understand cause am pretty bad at explaining but if you do, is there anyway to fix the issue.

thanks...

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

If you're using RTK, you may use skip:

const [skip, setSkip] = useState(true);
const { isUninitialized, isSuccess, isLoading } = useSomeQuery(token, {
  skip
});

and set skip to false when the token is available

about 4 years ago · Juan Pablo Isaza Denunciar

0

since the token is a dependency to your fetch, it should go to the queryKey. Then you can disable the query via the enabled option for as long as the token is null.

const token = useTokenFromLocalStorage()

useQuery(
  ["user", token],
  () => fetchUser(token),
  {
    enabled: !!token
  }
)

if the token updates (changes from null to a value), and that re-renders your component, the query will run automatically because the query key changes. The query will not run if the token is null.

about 4 years ago · Juan Pablo Isaza Denunciar
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