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

141
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
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