Fix validation behavior and add country codes

This commit is contained in:
Hazem Krimi
2021-05-02 04:00:06 +01:00
parent b010568e4e
commit 52b200beb3
2 changed files with 521 additions and 272 deletions
+99 -24
View File
@@ -2,21 +2,35 @@ import * as Yup from 'yup';
import { useFormik } from 'formik';
import { useState } from 'react';
import { useHistory } from 'react-router-dom';
import { useMutation, useReactiveVar } from '@apollo/client';
import { Box, Button, Input, Select, Text, Alert } from '../../../components';
import { useMutation, useQuery, useReactiveVar } from '@apollo/client';
import {
Box,
Button,
Input,
Select,
Text,
Alert,
Spinner,
} from '../../../components';
import { theme } from '../../../themes';
import { Wrapper } from './styles';
import {
GetCountryCodesQuery,
GetCountryCodesQueryVariables,
UpdateUserInfoMutation,
UpdateUserInfoMutationVariables,
} from '../../../graphql/types';
import { UPDATE_USER_INFO } from '../../../graphql/auth.api';
import { GET_COUNTRY_CODES, UPDATE_USER_INFO } from '../../../graphql/auth.api';
import { userVar } from '../../../graphql/state';
const AdditionalInfo = () => {
const history = useHistory();
const [error, setError] = useState<string>('');
const currentUser = useReactiveVar(userVar);
const { data: countryCodes, loading: countryCodesLoading } = useQuery<
GetCountryCodesQuery,
GetCountryCodesQueryVariables
>(GET_COUNTRY_CODES);
const [updateUserInfo, { loading }] = useMutation<
UpdateUserInfoMutation,
@@ -47,16 +61,28 @@ const AdditionalInfo = () => {
firstName: Yup.string().required('First Name is required'),
lastName: Yup.string().required('Last Name is required'),
prefix: Yup.string().required('Prefix is required'),
number: Yup.number().required('Number is required'),
number: Yup.number()
// prettier-ignore
.typeError('Phone must be a number')
.required('Phone is required'),
place: Yup.string().required('Address is required'),
city: Yup.string().required('City is required'),
country: Yup.string().required('Country is required'),
zip: Yup.number()
// prettier-ignore
.typeError('Zip must be a number')
.required('Zip is required'),
}),
onSubmit: (
{ firstName, lastName, prefix, number, place, city, country, zip },
{ resetForm }
) => {
try {
onSubmit: ({
firstName,
lastName,
prefix,
number,
place,
city,
country,
zip,
}) =>
updateUserInfo({
variables: {
id: currentUser?.id!,
@@ -66,14 +92,7 @@ const AdditionalInfo = () => {
phone: { prefix, number },
address: { place, city, country, zip },
},
});
} catch (err) {
setError(err.message);
setTimeout(() => setError(''), 3000);
} finally {
resetForm();
}
},
}),
});
return (
@@ -94,6 +113,7 @@ const AdditionalInfo = () => {
Tell us more about yourself
</Text>
</Box>
{!countryCodesLoading ? (
<form onSubmit={form.handleSubmit}>
<Box
display='grid'
@@ -107,7 +127,7 @@ const AdditionalInfo = () => {
value={form.values.firstName}
onChange={form.handleChange}
onBlur={form.handleBlur}
error={!!form.errors.firstName}
error={form.touched.firstName && !!form.errors.firstName}
errorMessage={form.errors.firstName}
/>
<Input
@@ -116,7 +136,7 @@ const AdditionalInfo = () => {
value={form.values.lastName}
onChange={form.handleChange}
onBlur={form.handleBlur}
error={!!form.errors.lastName}
error={form.touched.lastName && !!form.errors.lastName}
errorMessage={form.errors.lastName}
/>
<Box
@@ -127,13 +147,33 @@ const AdditionalInfo = () => {
<Select
name='prefix'
label='Country Code'
options={[
{ value: '+216', label: '+216' },
{ value: '+213', label: '+213' },
]}
options={
countryCodes?.getCountryCode
? [
{
value: '',
label: 'Choose',
},
...countryCodes.getCountryCode.map(
({ prefix, country }) => ({
value: prefix,
label: `+${prefix} (${country})`,
})
),
]
: [
{
value: '',
label: 'Choose',
},
{ value: '216', label: '+216' },
]
}
onChange={form.handleChange}
onBlur={form.handleBlur}
value={form.values.prefix}
error={form.touched.prefix && !!form.errors.prefix}
errorMessage={form.errors.prefix}
/>
<Input
name='number'
@@ -142,6 +182,8 @@ const AdditionalInfo = () => {
onChange={form.handleChange}
onBlur={form.handleBlur}
value={form.values.number}
error={form.touched.number && !!form.errors.number}
errorMessage={form.errors.number}
/>
</Box>
<Input
@@ -150,6 +192,8 @@ const AdditionalInfo = () => {
onChange={form.handleChange}
onBlur={form.handleBlur}
value={form.values.place}
error={form.touched.place && !!form.errors.place}
errorMessage={form.errors.place}
/>
<Input
name='city'
@@ -157,18 +201,44 @@ const AdditionalInfo = () => {
onChange={form.handleChange}
onBlur={form.handleBlur}
value={form.values.city}
error={form.touched.city && !!form.errors.city}
errorMessage={form.errors.city}
/>
<Box
display='grid'
gridTemplateColumns='2fr 1fr'
columnGap='10px'
>
<Input
<Select
name='country'
label='Country'
options={
countryCodes?.getCountryCode
? [
{
value: '',
label: 'Choose',
},
...countryCodes.getCountryCode.map(
({ country }) => ({
value: country,
label: country,
})
),
]
: [
{
value: '',
label: 'Choose',
},
{ value: 'Tunisia', label: 'Tunisia' },
]
}
onChange={form.handleChange}
onBlur={form.handleBlur}
value={form.values.country}
error={form.touched.country && !!form.errors.country}
errorMessage={form.errors.country}
/>
<Input
name='zip'
@@ -176,6 +246,8 @@ const AdditionalInfo = () => {
onChange={form.handleChange}
onBlur={form.handleBlur}
value={form.values.zip}
error={form.touched.zip && !!form.errors.zip}
errorMessage={form.errors.zip}
/>
</Box>
<Box marginTop='0.5rem'>
@@ -192,6 +264,9 @@ const AdditionalInfo = () => {
{error && <Alert color='error' text={error} />}
</Box>
</form>
) : (
<Spinner fullScreen />
)}
</Box>
</Box>
</Wrapper>
+195 -21
View File
@@ -1,9 +1,9 @@
import * as Yup from 'yup';
import { useFormik } from 'formik';
import { useHistory } from 'react-router';
import { useMutation, useReactiveVar } from '@apollo/client';
import { useMutation, useQuery, useReactiveVar } from '@apollo/client';
import { useState } from 'react';
import { roleVar, userVar } from '../../graphql/state';
import { roleVar, tokenVar, userVar } from '../../graphql/state';
import {
Box,
Button,
@@ -12,6 +12,8 @@ import {
Input,
Select,
Alert,
Spinner,
Modal,
} from '../../components';
import { Wrapper } from './styles';
import { ArrowLeft, Profile, Security } from '../../assets';
@@ -20,19 +22,33 @@ import {
UpdateUserPasswordMutation,
UpdateUserInfoMutationVariables,
UpdateUserPasswordMutationVariables,
GetCountryCodesQuery,
GetCountryCodesQueryVariables,
DeleteUserMutation,
DeleteUserMutationVariables,
} from '../../graphql/types';
import { UPDATE_USER_INFO, UPDATE_USER_PASSWORD } from '../../graphql/auth.api';
import {
DELETE_USER,
GET_COUNTRY_CODES,
UPDATE_USER_INFO,
UPDATE_USER_PASSWORD,
} from '../../graphql/auth.api';
const Settings = () => {
const history = useHistory();
const role = useReactiveVar(roleVar);
const currentUser = useReactiveVar(userVar);
const { data: countryCodes, loading: countryCodesLoading } = useQuery<
GetCountryCodesQuery,
GetCountryCodesQueryVariables
>(GET_COUNTRY_CODES);
const [selectedSection, setSelectedSection] = useState<
'general' | 'security'
>('general');
const [error, setError] = useState<string>('');
const [success, setSuccess] = useState<boolean>(false);
const [deleteAccountModal, setDeleteAccountModal] = useState<boolean>(false);
const [updateUserInfo, { loading: generalLoading }] = useMutation<
UpdateUserInfoMutation,
@@ -72,10 +88,13 @@ const Settings = () => {
firstName: Yup.string().required('First Name is required'),
lastName: Yup.string().required('Last Name is required'),
prefix: Yup.string().required('Prefix is required'),
number: Yup.number().required('Number is required'),
// prettier-ignore
number: Yup.number().typeError('Phone must be a number').required('Phone is required'),
place: Yup.string().required('Address is required'),
city: Yup.string().required('City is required'),
country: Yup.string().required('Country is required'),
// prettier-ignore
zip: Yup.number().typeError('Zip must be a number').required('Zip is required'),
}),
onSubmit: ({
firstName,
@@ -122,16 +141,19 @@ const Settings = () => {
},
validationSchema: Yup.object().shape({
oldPassword: Yup.string()
.required('Password is required')
.min(6, 'Password is 6 characters minimum'),
.required('Old password is required')
.min(6, 'Old password is 6 characters minimum'),
newPassword: Yup.string()
.required('New password is required')
.notOneOf(
[Yup.ref('oldPassword')],
'New password should not be old password'
)
.required('New password is required')
.min(6, 'New password is 6 characters minimum'),
confirmNewPassword: Yup.string().oneOf(
confirmNewPassword: Yup.string()
.required('Confirm new password is required')
.oneOf(
[Yup.ref('newPassword')],
"Confirm new password doesn't match with new password"
),
@@ -145,6 +167,43 @@ const Settings = () => {
}),
});
const [deleteUser] = useMutation<
DeleteUserMutation,
DeleteUserMutationVariables
>(DELETE_USER, {
onCompleted() {
localStorage.removeItem('token');
tokenVar(undefined);
userVar(undefined);
roleVar(undefined);
setDeleteAccountModal(false);
history.push('/signup');
},
onError({ graphQLErrors }) {
setDeleteAccountModal(false);
setError(graphQLErrors[0]?.extensions?.info);
setTimeout(() => setError(''), 3000);
},
});
const deleteAccountForm = useFormik({
initialValues: {
password: '',
},
validationSchema: Yup.object().shape({
password: Yup.string()
.required('Password is required')
.min(6, 'Password is 6 characters minimum'),
}),
onSubmit: ({ password }, { resetForm }) => {
try {
deleteUser({ variables: { id: currentUser?.id!, password } });
} finally {
resetForm();
}
},
});
return (
<Wrapper>
<Box>
@@ -204,6 +263,8 @@ const Settings = () => {
)}
</Box>
{selectedSection === 'general' && (
<>
{!countryCodesLoading ? (
<form onSubmit={generalForm.handleSubmit}>
<Box
display='grid'
@@ -214,19 +275,27 @@ const Settings = () => {
<Input
name='firstName'
label='First Name'
color={role || 'client'}
value={generalForm.values.firstName}
onChange={generalForm.handleChange}
onBlur={generalForm.handleBlur}
error={!!generalForm.errors.firstName}
error={
generalForm.touched.firstName &&
!!generalForm.errors.firstName
}
errorMessage={generalForm.errors.firstName}
/>
<Input
name='lastName'
label='Last Name'
color={role || 'client'}
value={generalForm.values.lastName}
onChange={generalForm.handleChange}
onBlur={generalForm.handleBlur}
error={!!generalForm.errors.lastName}
error={
generalForm.touched.lastName &&
!!generalForm.errors.lastName
}
errorMessage={generalForm.errors.lastName}
/>
<Box
@@ -237,55 +306,106 @@ const Settings = () => {
<Select
name='prefix'
label='Country Code'
options={[
{ value: '+216', label: '+216' },
{ value: '+213', label: '+213' },
]}
color={role || 'client'}
options={
countryCodes?.getCountryCode
? countryCodes.getCountryCode.map(
({ prefix, country }) => ({
value: prefix,
label: `+${prefix} (${country})`,
})
)
: [{ value: '216', label: '+216' }]
}
onChange={generalForm.handleChange}
onBlur={generalForm.handleBlur}
value={generalForm.values.prefix}
select={generalForm.values.prefix}
error={
generalForm.touched.prefix &&
!!generalForm.errors.prefix
}
errorMessage={generalForm.errors.prefix}
/>
<Input
name='number'
type='tel'
label='Phone'
color={role || 'client'}
onChange={generalForm.handleChange}
onBlur={generalForm.handleBlur}
value={generalForm.values.number}
error={
generalForm.touched.number &&
!!generalForm.errors.number
}
errorMessage={generalForm.errors.number}
/>
</Box>
<Input
name='place'
label='Address'
color={role || 'client'}
onChange={generalForm.handleChange}
onBlur={generalForm.handleBlur}
value={generalForm.values.place}
error={
generalForm.touched.place && !!generalForm.errors.place
}
errorMessage={generalForm.errors.place}
/>
<Input
name='city'
label='City'
color={role || 'client'}
onChange={generalForm.handleChange}
onBlur={generalForm.handleBlur}
value={generalForm.values.city}
error={
generalForm.touched.city && !!generalForm.errors.city
}
errorMessage={generalForm.errors.city}
/>
<Box
display='grid'
gridTemplateColumns='2fr 1fr'
columnGap='10px'
>
<Input
<Select
name='country'
label='Country'
color={role || 'client'}
options={
countryCodes?.getCountryCode
? countryCodes.getCountryCode.map(
({ country }) => ({
value: country,
label: country,
})
)
: [{ value: 'Tunisia', label: 'Tunisia' }]
}
onChange={generalForm.handleChange}
onBlur={generalForm.handleBlur}
value={generalForm.values.country}
select={generalForm.values.country}
error={
generalForm.touched.country &&
!!generalForm.errors.country
}
errorMessage={generalForm.errors.country}
/>
<Input
name='zip'
label='Zip Code'
color={role || 'client'}
onChange={generalForm.handleChange}
onBlur={generalForm.handleBlur}
value={generalForm.values.zip}
error={
generalForm.touched.zip && !!generalForm.errors.zip
}
errorMessage={generalForm.errors.zip}
/>
</Box>
<Box
@@ -296,7 +416,7 @@ const Settings = () => {
>
<Button
variant='primary-action'
color='client'
color={role || 'client'}
text='Save'
type='submit'
loading={generalLoading}
@@ -305,8 +425,40 @@ const Settings = () => {
</Box>
</Box>
</form>
) : (
<Box display='grid' alignItems='center' justifyContent='center'>
<Spinner color={role || 'client'} />
</Box>
)}
</>
)}
{selectedSection === 'security' && (
<>
{deleteAccountModal && (
<Modal
color={role || 'client'}
title='Delete Account'
description='Enter password to confirm account deletion.
If you delete your account you cannot recover any of your projects.'
onClose={() => setDeleteAccountModal(false)}
onConfirm={deleteAccountForm.handleSubmit}
>
<Input
type='password'
placeholder='Password'
name='password'
value={deleteAccountForm.values.password}
onChange={deleteAccountForm.handleChange}
onBlur={deleteAccountForm.handleBlur}
color={role || 'client'}
error={
deleteAccountForm.touched.password &&
!!deleteAccountForm.errors.password
}
errorMessage={deleteAccountForm.errors.password}
/>
</Modal>
)}
<form onSubmit={securityForm.handleSubmit}>
<Box
display='grid'
@@ -317,42 +469,63 @@ const Settings = () => {
<Input
name='oldPassword'
label='Old Password'
color={role || 'client'}
type='password'
value={securityForm.values.oldPassword}
onChange={securityForm.handleChange}
onBlur={securityForm.handleBlur}
error={!!securityForm.errors.oldPassword}
error={
securityForm.touched.oldPassword &&
!!securityForm.errors.oldPassword
}
errorMessage={securityForm.errors.oldPassword}
/>
<Input
name='newPassword'
label='New Password'
color={role || 'client'}
type='password'
value={securityForm.values.newPassword}
onChange={securityForm.handleChange}
onBlur={securityForm.handleBlur}
error={!!securityForm.errors.newPassword}
error={
securityForm.touched.newPassword &&
!!securityForm.errors.newPassword
}
errorMessage={securityForm.errors.newPassword}
/>
<Input
name='confirmNewPassword'
label='Confirm New Password'
color={role || 'client'}
type='password'
value={securityForm.values.confirmNewPassword}
onChange={securityForm.handleChange}
onBlur={securityForm.handleBlur}
error={!!securityForm.errors.confirmNewPassword}
error={
securityForm.touched.confirmNewPassword &&
!!securityForm.errors.confirmNewPassword
}
errorMessage={securityForm.errors.confirmNewPassword}
/>
<Box
marginTop='0.5rem'
display='flex'
justifyContent='space-between'
justifyContent={
role === 'client' ? 'space-between' : 'flex-end'
}
>
<Button variant='text' color='error' text='Delete Account' />
{role === 'client' && (
<Button
variant='text'
color='error'
text='Delete Account'
onClick={() => setDeleteAccountModal(true)}
/>
)}
<Button
variant='primary-action'
color='client'
color={role || 'client'}
text='Save'
type='submit'
loading={securityLoading}
@@ -361,6 +534,7 @@ const Settings = () => {
</Box>
</Box>
</form>
</>
)}
</Box>
</Box>