From a6ae37cdac3f037186ff321af9975f4a14fdf02f Mon Sep 17 00:00:00 2001 From: Nikolai R Kristiansen Date: Tue, 5 Oct 2021 23:40:11 +0200 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=20Refactor=20using=20react-hook-form?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 1 + src/modules/register/UserRegister.js | 329 +++++++++------------------ yarn.lock | 5 + 3 files changed, 114 insertions(+), 221 deletions(-) diff --git a/package.json b/package.json index 2022459..4c72c06 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ "native-base": "^3.2.0", "prop-types": "^15.7.2", "react": "^17.0.2", + "react-hook-form": "^7.17.1", "react-is": "^17.0.2", "react-native": "0.66.0-rc.4", "react-native-confetti": "^0.1.0", diff --git a/src/modules/register/UserRegister.js b/src/modules/register/UserRegister.js index b8c5aea..5c84247 100644 --- a/src/modules/register/UserRegister.js +++ b/src/modules/register/UserRegister.js @@ -1,245 +1,132 @@ -import React, { useState, useEffect, useRef } from 'react'; +import React from 'react'; import { Container, Input, Spinner, Button, Text, Icon, Toast, FormControl } from 'native-base'; import { StyleSheet, View } from 'react-native'; import * as EmailValidator from 'email-validator'; +import { useForm, Controller } from 'react-hook-form'; import theme from '../../theme'; import useUserRegister from './useUserRegister'; +const FormInput = ({ + control, + errors, + name, + label, + rules = { + required: true, + }, + returnKeyType = 'next', + ...rest +}) => { + return ( + ( + + {label} + + {errors[name] && ( + + kan ikke være tomt. + + + )} + + )} + name={name} + defaultValue="" + /> + ); +}; + +const Registerbutton = ({ isDisabled, onPress }) => ( + +); + +const NonFieldErrors = ({ errors }) => { + if (Object.keys(errors).length !== 0 && 'non_field_errors' in errors) { + const err = errors.non_field_errors; + const errorFormatted = err ? err[0] : 'Kunne ikke registrere bruker, prøv igjen...'; + return ( + + {errorFormatted} + + ); + } + if (Object.keys(errors).length !== 0 && 'detail' in errors) { + const err = errors.detail; + const errorFormatted = err || 'Kunne ikke registrere bruker, prøv igjen...'; + return ( + + {errorFormatted} + + ); + } + + return ; +}; + const UserRegister = () => { - const [firstName, setFirstName] = useState(''); - const [lastName, setLastName] = useState(''); - const [email, setEmail] = useState(''); - const [phoneNumber, setPhoneNumber] = useState(''); - const [password, setPassword] = useState(''); - const [errors, setErrors] = useState({}); - const [touched, setTouched] = useState(new Set()); const { isRegisteringUser, onRegisterPress } = useUserRegister(); + // TODO: email validation + // TODO: focus next field - const emailInputRef = useRef(); - const lastNameInputRef = useRef(); - const phoneInputRef = useRef(); - const passwordInputRef = useRef(); + const { + control, + handleSubmit, + formState: { errors, isDirty, isValid }, + } = useForm(); + const isDisabled = !isDirty || isRegisteringUser || !isValid; + const onSubmit = (data) => { + console.log(data); + // if (!canSubmitForm()) { + // Toast.show({ + // text: 'Noen av feltene er ikke fylt ut riktig', + // position: 'bottom', + // buttonText: 'OK', + // duration: 1500, + // }); + // return; + // } - const validateForm = (triggeredBy) => { - const values = { firstName, lastName, email, phoneNumber, password }; - - const freshErrors = { ...errors }; - const freshTouched = new Set(touched).add(triggeredBy); - - /* No empty fields */ - Object.entries(values).forEach(([key, value]) => { - if (value === '') { - freshErrors[key] = 'kan ikke være tomt'; - } else if (key === 'email' && !EmailValidator.validate(value)) { - freshErrors[key] = 'er ikke en gyldig e-post'; - } else { - delete freshErrors[key]; - } - }); - setErrors(freshErrors); - setTouched(freshTouched); - }; - - const fieldHasError = (field) => { - return touched.has(field) && field in errors; - }; - - const canSubmitForm = () => { - return Object.keys(errors).length === 0; - }; - - // useEffect(() => { - // if (prevRegisterError !== registerError) { - // setErrors(registerError); - // } - // }, []); - - const showFieldError = (field) => { - if (!fieldHasError(field)) { - return null; - } - return ( - - {errors[field]} - - ); - }; - - const firstNameInput = () => { - return ( - - Fornavn - { - setFirstName(value); - validateForm('firstName'); - }} - onSubmitEditing={() => { - lastNameInputRef.current.focus(); - }} - value={firstName} - /> - {fieldHasError('firstName') && } - - ); - }; - - const lastNameInput = () => { - return ( - - Etternavn - { - setLastName(value); - validateForm('lastName'); - }} - onSubmitEditing={() => { - emailInputRef.current.focus(); - }} - value={lastName} - /> - {fieldHasError('lastName') && } - - ); - }; - - const emailInput = () => { - return ( - - E-post - { - setEmail(value); - validateForm('email'); - }} - onSubmitEditing={() => { - phoneInputRef.current.focus(); - }} - value={email} - /> - {fieldHasError('email') && } - - ); - }; - - const phoneNumberInput = () => { - return ( - - Mobilnummer - { - setPhoneNumber(value); - validateForm('phoneNumber'); - }} - onSubmitEditing={() => { - passwordInputRef.current.focus(); - }} - value={phoneNumber} - /> - {fieldHasError('phoneNumber') && } - - ); - }; - const passwordInput = () => { - return ( - - Passord - { - setPassword(value); - validateForm('password'); - }} - onSubmitEditing={onRegisterPress} - value={password} - /> - {fieldHasError('password') && } - - ); - }; - const showNonFieldError = () => { - if (Object.keys(errors).length !== 0 && 'non_field_errors' in errors) { - const err = errors.non_field_errors; - const errorFormatted = err ? err[0] : 'Kunne ikke registrere bruker, prøv igjen...'; - return ( - - {errorFormatted} - - ); - } - if (Object.keys(errors).length !== 0 && 'detail' in errors) { - const err = errors.detail; - const errorFormatted = err || 'Kunne ikke registrere bruker, prøv igjen...'; - return ( - - {errorFormatted} - - ); - } - - return ; - }; - - const onSubmit = () => { - if (!canSubmitForm()) { - Toast.show({ - text: 'Noen av feltene er ikke fylt ut riktig', - position: 'bottom', - buttonText: 'OK', - duration: 1500, - }); - return; - } - - onRegisterPress(firstName, lastName, email, phoneNumber, password); - }; - - const registerbutton = () => { - const isDisabled = touched.size === 0 || isRegisteringUser || !canSubmitForm(); - - return ( - - ); + // onRegisterPress(firstName, lastName, email, phoneNumber, password); }; return ( - {firstNameInput()} - {showFieldError('firstName')} - {lastNameInput()} - {showFieldError('lastName')} - {emailInput()} - {showFieldError('email')} - {phoneNumberInput()} - {showFieldError('phoneNumber')} - {passwordInput()} - {showFieldError('password')} - {showNonFieldError()} - {registerbutton()} + + + + + + + {isRegisteringUser && } ); }; + export default UserRegister; const styles = StyleSheet.create({ diff --git a/yarn.lock b/yarn.lock index 180bd73..bc3dac2 100644 --- a/yarn.lock +++ b/yarn.lock @@ -7495,6 +7495,11 @@ react-dom@^17.0.2: object-assign "^4.1.1" scheduler "^0.20.2" +react-hook-form@^7.17.1: + version "7.17.1" + resolved "https://registry.yarnpkg.com/react-hook-form/-/react-hook-form-7.17.1.tgz#dc257a5e34b3c353460ecdbbba5236e066cf80b1" + integrity sha512-9nQ+qKFHFpnWzQHdDh6F4Egxa8iJkue1KU921F8qqeyUVbPPjgQZDXaQyNHABEYjRh0ndjTI24GDA+lwm2lQdg== + "react-is@^16.12.0 || ^17.0.0", react-is@^17.0.1, react-is@^17.0.2: version "17.0.2" resolved "https://registry.yarnpkg.com/react-is/-/react-is-17.0.2.tgz#e691d4a8e9c789365655539ab372762b0efb54f0"