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

145
Views
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
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!