Reputation: 2804
AWS amplify documentation shows
let session = Auth.currentSession();
// CognitoUserSession => { idToken, refreshToken, accessToken }
to retrieve Current Session which is working fine.
However, I'm not sure how to implement this into my React app with Redux. All the data in store goes away when user reload the webpage along with all UIs for logged in user.
I want to maintain logged-in stage as it is even if user refresh the page as long as CognitoUserSession is valid and maybe keep some data that I already have in the store.
What is the best way to implement this?
Upvotes: 1
Views: 1988
Reputation: 2633
aws-amplify makes heavy use of localStorage. You can too.
You can also use sessionStorage, which is the same thing except everything is deleted after the window closes.
If you want save something:
window.localStorage.setItem(“itemKey”, “itemString”);
To get it back:
const item = window.localStorage.getItem(“itemKey”);
Please note: if you want to save an object you need to JSON.stringify it and then JSON.parse it when you retrieve it. You can only store strings.
I would not store sensitive information on localStorage as a general rule.
Also, I tend to run a session check of some kind on certain components when they mount or update. For instance, you could add:
if (!this.props.session) { // stored session object in redux
Auth.currentSession().then((session) => {
handleSession({ session }); // redux action to store session
});
}
The idea is: if the page refreshes, the components with these session checks will mount, run the if statement above, realize session is empty and, try to retrieve a new session object from Auth. If Auth returns an error because the user is no longer authenticated, you could add additional logic to redirect to your login screen.
Upvotes: 2