Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added fix for Signup.js refresh losing state when user navigates back… #624

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion _chapters/signup-with-aws-cognito.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,27 @@ description: To implement a signup form in our React.js app using Amazon Cognito
comments_id: signup-with-aws-cognito/130
---

Now let's go ahead and implement the `handleSubmit` and `handleConfirmationSubmit` functions and connect it up with our AWS Cognito setup.
Now let's go ahead and implement the `handleSubmit` and `handleConfirmationSubmit` functions and connect it up with our AWS Cognito setup. We will also add some code to control for the user navigating away from the page to get their AWS confirmation code, which otherwise may cause your page to refresh and lose state (this issue usually appears on mobile devices).

{%change%} First, add `useEffect` to the `import`s in the top line of `src/containers/Signup.js`, so it looks like this:

``` javascript
import React, { useState, useEffect } from "react";
```

{%change%} Then we will add a variable that will serve as our key to store and retrieve user data from `localStorage`, and a check for that data when someone navigates to, or refreshes, the page. This should be added right below the `useState()` variables:

``` javascript
const tempAddressForUserInfo = 'tempNewUserData';

useEffect(() => {
const tempNewUser = window.localStorage.getItem(tempAddressForUserInfo);

if (tempNewUser) {
setNewUser(JSON.parse(tempNewUser));
}
}, []);
```

{%change%} Replace our `handleSubmit` and `handleConfirmationSubmit` functions in `src/containers/Signup.js` with the following.

Expand All @@ -23,6 +43,8 @@ async function handleSubmit(event) {
username: fields.email,
password: fields.password,
});

window.localStorage.setItem(tempAddressForUserInfo, JSON.stringify(newUser));
setIsLoading(false);
setNewUser(newUser);
} catch (e) {
Expand All @@ -42,6 +64,7 @@ async function handleConfirmationSubmit(event) {

userHasAuthenticated(true);
history.push("/");
window.localStorage.removeItem(tempAddressForUserInfo);
} catch (e) {
onError(e);
setIsLoading(false);
Expand Down