Skip to content
Advertisement

React doesn’t refresh state in LocalStorage

how are you?

Im doing a proof of concept using React and Cognito Hosted UI. I have this code here using react router dom:

JavaScript

Im using S3 as a static website hosting, thats why i point to S3 cloudfront distribution apex. Then, in my App function (residex inside App.js file), i make this validation every times the user access, to verify if this comes from a redirect, and if comes, i exchange the auth_code for a JWT token, that will be used with API Gateway:

JavaScript

The problem is that after i make the authentication, either using google or login and password, i receive the code, i authenticate on cognito using a lambda on backend (on /dev/auth route, behind the Gateway), the lambda performs the authentication well, but my frontend page enters in a loop, and after print null a bunch of times (from the line console.log(authCode), i receive an error, telling that im in a loop). Im very newbie in react, im doing this POC to understand the concept and to show this proccess to a client.

Thanks in advance! I can’t share the code as entire because that are stored in private company repository.

My complete code:

JavaScript

UPDATE 1: I think that the error is here:

JavaScript

when the Lambda API returns an error, the workflow goes well, but the localStorage isn’t filled with the JWT token.

I need to wait the response from the lambda function, insert JWT in localStorage, and then moves the user to /home url.

UPDATE 2: After some hours of debugging, and a lot of help, i finaly discover the problem. The problem was related to this line:

JavaScript

Cause we already have a useEffect statement that looks for the code and perform some actions, using this same code we enter in a loop statement. I just delete that and it works! thanks.

Advertisement

Answer

I can see that you have written you api call code inside a functional component and i am assuming you want hit the api only once to achieve that you can write ur code inside useEffect

JavaScript
Advertisement