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

151
Visualizações
React JS context update state from async function

In the auth context i have a function for login that set the state and some data in cookies. Also i set some Protected routes for some pages to acces only if you are loged in and i determinate if an account is logged from the state. If i refresh the page the default state is null. I want to set the state with some data from the API(decrypted token). On initial declare of the state i had the following code:

let [username, setUsername] = useState(
    sessionStorage.getItem('auth')
        ? jwtDecode(check_jwt())
        : null
)

The check_jwt function is an async function that decrypt the token with a public user key on frontend and then sent it to the api(with fetch method) to decrypt and validate the token. If i set the state like above after refresh the user is sent to login page cuz the information dose't arrive "in time". All of this is set on a react component that i can't made it async, => that mean i can't use await before check_jwt(). What can i do to wait for the awnser and after that execute the rest of code. I return in the context provider the state and i will call it in the Protected route function.

Thx and sorry for my bad english :)

about 4 years ago · Santiago Gelvez
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