Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { useState } from 'react';
- import { isNull, capitalize, lowerCase } from 'lodash';
- import { Input, Button, Form } from 'antd';
- import { withFirebase } from 'react-redux-firebase';
- // import { withRouter, SingletonRouter } from 'next/router';
- import firebase from 'firebase';
- import { Dispatch } from 'redux';
- import { push } from 'connected-react-router';
- import { WrappedFormUtils } from 'antd/lib/form/Form';
- // import { CLIENT } from '../../pages/register';
- export type RegisterFormProps = {
- role: string | null;
- firebase: firebase.app.App;
- dispatch: Dispatch;
- form: WrappedFormUtils;
- // router: SingletonRouter;
- };
- const RegisterForm: React.FunctionComponent<RegisterFormProps> = props => {
- const { role, firebase, dispatch } = props;
- const { getFieldDecorator, getFieldsError, isFieldTouched } = props.form;
- if (isNull(role)) {
- return null; // renders nothing!
- }
- // const emailError = isFieldTouched('email') && getFieldError('email');
- // const passwordError = isFieldTouched('password') && getFieldError('password');
- // const confirmError = isFieldTouched('confifm') && getFieldError('confirm');
- // const [email, setEmail] = useState('adoji92@gmail.com');
- // const [password, setPassword] = useState('adjadj1234');
- // const [password2, setPassword2] = useState('adjadj1234');
- const [email, setEmail] = useState<string>('');
- const [password, setPassword] = useState<string>('');
- const [setPassword2] = useState<string>('');
- const onChangeBase = (
- setter: React.Dispatch<React.SetStateAction<string>>,
- ) => (event: React.ChangeEvent<HTMLInputElement>) =>
- setter(event.target.value);
- // const isValidEmail = (email: string) => true; // TODO: replace dummy
- // const isValidPassword = (password: string) => true; // TODO: replace dummy
- // const isFormValid = (email: string, password: string, password2: string) =>
- // isValidEmail(email) && isValidPassword(password) && password === password2; // TODO: return [boolean, errorCode] to display proper errorCode
- // // OR rename to validateForm, then return { isValid: boolean, errorCode: number }
- function hasErrors(fieldsError: any) { // FIXME: Typescript Error: ANY
- return Object.keys(fieldsError).some(field => fieldsError[field]);
- }
- let confirmDirty = false;
- const handleConfirmBlur = (e: any) => {
- const value = e.target.value;
- confirmDirty = confirmDirty || !!value ;
- };
- const compareToFirstPassword = (rule: any, value: any, callback: any) => {
- const form = props.form;
- console.log(rule);
- if (value && value !== form.getFieldValue('password')) {
- callback('Two passwords that you enter is inconsistent!');
- } else {
- callback();
- }
- };
- const validateToNextPassword = (rule: any, value: any, callback: any) => {
- const form = props.form;
- if (value && confirmDirty) {
- form.validateFields(['confirm'], { force: true });
- }
- callback();
- };
- const onSubmit = async (email: string, password: string, role: string) => {
- let hasError = false;
- try {
- await firebase.auth().createUserWithEmailAndPassword(email, password);
- } catch (error) {
- // TODO: switch with error.code
- console.error('error', error); // TODO: delete on production build
- hasError = true;
- }
- if (hasError) {
- // NOTE: return in catch clause is anti-pattern
- return;
- }
- try {
- const user = firebase.auth().currentUser;
- if (!isNull(user)) {
- const uid = user.uid;
- const convertedRole = lowerCase(role);
- await firebase
- .firestore()
- .collection('users')
- .doc(uid)
- .set({
- role: convertedRole,
- });
- }
- } catch (error) {
- console.error('error2', error); // TODO: delete on production build
- hasError = true;
- }
- if (hasError) {
- return;
- }
- try {
- const user = firebase.auth().currentUser;
- if (!isNull(user)) {
- await user.sendEmailVerification();
- }
- } catch (error) {
- console.error('error3', error); // TODO: delete on production build
- hasError = true;
- }
- if (hasError) {
- return;
- }
- dispatch(push('/email-verification-required'));
- // TODO: notify user that registration was sucessfuly and you needs email verification
- };
- return (
- <div>
- <h1>Register as {capitalize(role)}</h1>
- <Form>
- <Form.Item
- label="E-mail"
- // validateStatus={emailError ? 'error' : ''}
- >
- {getFieldDecorator('email', {
- rules: [
- {
- type: 'email',
- message: 'The input is not valid E-mail!',
- },
- {
- required: true,
- message: 'Please input your E-mail!',
- },
- ],
- })
- (<Input
- placeholder="E-mail"
- size="large"
- onChange={onChangeBase(setEmail)}
- />)}
- </Form.Item>
- <Form.Item
- label="Password" hasFeedback={true}
- // validateStatus={passwordError ? 'error' : ''}
- >
- {getFieldDecorator('password', {
- rules: [
- {
- required: true,
- message: 'Please input your password!',
- },
- {
- validator: validateToNextPassword,
- },
- ],
- })(<Input.Password
- placeholder="Password"
- size="large"
- onChange={onChangeBase(setPassword)}
- />)}
- </Form.Item>
- <Form.Item
- label="Confirm Password" hasFeedback={true}
- // validateStatus={confirmError ? 'error' : ''}
- >
- {getFieldDecorator('confirm', {
- rules: [
- {
- required: true,
- message: 'Please confirm your password!',
- },
- {
- validator: compareToFirstPassword,
- },
- ],
- })(<Input.Password
- onBlur={handleConfirmBlur}
- placeholder="Password confirmation"
- size="large"
- onChange={onChangeBase(setPassword2)}
- />)}
- </Form.Item>
- <br />
- <Form.Item>
- <Button
- type="primary"
- htmlType="submit"
- disabled={
- hasErrors(getFieldsError())
- || !isFieldTouched('email')
- || !isFieldTouched('password')
- || !isFieldTouched('confirm')
- }
- block={true}
- // tslint:disable-next-line jsx-no-lambda
- onClick={evt => {
- evt.preventDefault();
- onSubmit(email, password, role);
- }}
- >
- Register
- </Button>
- </Form.Item>
- </Form>
- {/* email: {email}
- <br />
- pw1: {password}
- <br />
- pw2: {password2}
- <br /> */}
- </div>
- );
- };
- const WrappedRegisterForm = Form.create({ name: 'register' })(RegisterForm);
- // export default RegisterForm;
- export default withFirebase(WrappedRegisterForm);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement