Skip to main content

18.09 Adding A Spinner

Auth.js

src\containers\Auth\Auth.js
import React, { Component } from "react";
import { connect } from "react-redux";
import Button from "../../components/UI/Button/Button";
import Input from "../../components/UI/Input/Input";
import Spinner from "../../components/UI/Spinner/Spinner";
import * as actions from "../../store/actions/index";
import classes from "./Auth.module.css";

class Auth extends Component {
state = {
controls: {
email: {
elementType: "input",
elementConfig: {
type: "email",
placeholder: "Mail Address",
},
value: "",
validation: {
required: true,
isEmail: true,
},
valid: false,
touched: false,
},
password: {
elementType: "input",
elementConfig: {
type: "password",
placeholder: "Password",
},
value: "",
validation: {
required: true,
minLength: 6,
},
valid: false,
touched: false,
},
},
isSignup: true,
};

checkValidity(value, rules) {
let isValid = true;
if (!rules) {
return true;
}

if (rules.required) {
isValid = value.trim() !== "" && isValid;
}

if (rules.minLength) {
isValid = value.length >= rules.minLength && isValid;
}

if (rules.maxLength) {
isValid = value.length <= rules.maxLength && isValid;
}

if (rules.isEmail) {
const pattern = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
isValid = pattern.test(value) && isValid;
}

if (rules.isNumeric) {
const pattern = /^\d+$/;
isValid = pattern.test(value) && isValid;
}

return isValid;
}

inputChangedHandler = (event, controlName) => {
const updatedControls = {
...this.state.controls,
[controlName]: {
...this.state.controls[controlName],
value: event.target.value,
valid: this.checkValidity(
event.target.value,
this.state.controls[controlName].validation
),
touched: true,
},
};
this.setState({ controls: updatedControls });
};

submitHandler = (event) => {
event.preventDefault();
this.props.onAuth(
this.state.controls.email.value,
this.state.controls.password.value,
this.state.isSignup
);
};

switchAuthModeHandler = () => {
this.setState((prevState) => {
return { isSignup: !prevState.isSignup };
});
};
render() {
const formElementsArray = [];
for (let key in this.state.controls) {
formElementsArray.push({
id: key,
config: this.state.controls[key],
});
}

let form = formElementsArray.map((formElement) => (
<Input
key={formElement.id}
elementType={formElement.config.elementType}
elementConfig={formElement.config.elementConfig}
value={formElement.config.value}
invalid={!formElement.config.valid}
shouldValidate={formElement.config.validation}
touched={formElement.config.touched}
changed={(event) => this.inputChangedHandler(event, formElement.id)}
/>
));

if (this.props.loading) {
form = <Spinner />;
}

let errorMessage = null;

if (this.props.error) {
errorMessage = <p>{this.props.error.message}</p>;
}

return (
<div className={classes.Auth}>
{errorMessage}
<form onSubmit={this.submitHandler}>
{form}
<Button btnType="Success">Submit</Button>
<Button clicked={this.switchAuthModeHandler} btnType="Danger">
SWITCH TO {this.state.isSignup ? "SIGNIN" : "SIGNUP"}
</Button>
</form>
</div>
);
}
}

const mapStateToProps = (state) => {
return {
loading: state.auth.loading,
error: state.auth.error,
};
};

const mapDispatchToProps = (dispatch) => {
return {
onAuth: (email, password, isSignup) =>
dispatch(actions.auth(email, password, isSignup)),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Auth);

auth.js

src\store\actions\auth.js
import axios from "axios";
import * as actionTypes from "./actionTypes";

export const authStart = () => {
return {
type: actionTypes.AUTH_START,
};
};

export const authSuccess = (token, userId) => {
return {
type: actionTypes.AUTH_SUCCESS,
idToken: token,
userId: userId,
};
};

export const authFail = (error) => {
return {
type: actionTypes.AUTH_FAIL,
error: error,
};
};

export const auth = (email, password, isSignup) => {
return (dispatch) => {
dispatch(authStart());
const authData = {
email: email,
password: password,
returnSecureToken: true,
};
let url =
"https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=AIzaSyDsmwPeH2yE7yqvoeYolCLgB9ju50rYivo";
if (!isSignup) {
url =
"https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=AIzaSyDsmwPeH2yE7yqvoeYolCLgB9ju50rYivo";
}
axios
.post(url, authData)
.then((response) => {
console.log(response);
dispatch(authSuccess(response.data.idToken, response.data.localId));
})
.catch((err) => {
dispatch(authFail(err.response.data.error));
});
};
};