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 { useFormik } from 'formik';
import { useState } from 'react'; import { useState } from 'react';
import { useHistory } from 'react-router-dom'; import { useHistory } from 'react-router-dom';
import { useMutation, useReactiveVar } from '@apollo/client'; import { useMutation, useQuery, useReactiveVar } from '@apollo/client';
import { Box, Button, Input, Select, Text, Alert } from '../../../components'; import {
Box,
Button,
Input,
Select,
Text,
Alert,
Spinner,
} from '../../../components';
import { theme } from '../../../themes'; import { theme } from '../../../themes';
import { Wrapper } from './styles'; import { Wrapper } from './styles';
import { import {
GetCountryCodesQuery,
GetCountryCodesQueryVariables,
UpdateUserInfoMutation, UpdateUserInfoMutation,
UpdateUserInfoMutationVariables, UpdateUserInfoMutationVariables,
} from '../../../graphql/types'; } 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'; import { userVar } from '../../../graphql/state';
const AdditionalInfo = () => { const AdditionalInfo = () => {
const history = useHistory(); const history = useHistory();
const [error, setError] = useState<string>(''); const [error, setError] = useState<string>('');
const currentUser = useReactiveVar(userVar); const currentUser = useReactiveVar(userVar);
const { data: countryCodes, loading: countryCodesLoading } = useQuery<
GetCountryCodesQuery,
GetCountryCodesQueryVariables
>(GET_COUNTRY_CODES);
const [updateUserInfo, { loading }] = useMutation< const [updateUserInfo, { loading }] = useMutation<
UpdateUserInfoMutation, UpdateUserInfoMutation,
@@ -47,16 +61,28 @@ const AdditionalInfo = () => {
firstName: Yup.string().required('First Name is required'), firstName: Yup.string().required('First Name is required'),
lastName: Yup.string().required('Last Name is required'), lastName: Yup.string().required('Last Name is required'),
prefix: Yup.string().required('Prefix 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'), place: Yup.string().required('Address is required'),
city: Yup.string().required('City is required'), city: Yup.string().required('City is required'),
country: Yup.string().required('Country 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: ( onSubmit: ({
{ firstName, lastName, prefix, number, place, city, country, zip }, firstName,
{ resetForm } lastName,
) => { prefix,
try { number,
place,
city,
country,
zip,
}) =>
updateUserInfo({ updateUserInfo({
variables: { variables: {
id: currentUser?.id!, id: currentUser?.id!,
@@ -66,14 +92,7 @@ const AdditionalInfo = () => {
phone: { prefix, number }, phone: { prefix, number },
address: { place, city, country, zip }, address: { place, city, country, zip },
}, },
}); }),
} catch (err) {
setError(err.message);
setTimeout(() => setError(''), 3000);
} finally {
resetForm();
}
},
}); });
return ( return (
@@ -94,6 +113,7 @@ const AdditionalInfo = () => {
Tell us more about yourself Tell us more about yourself
</Text> </Text>
</Box> </Box>
{!countryCodesLoading ? (
<form onSubmit={form.handleSubmit}> <form onSubmit={form.handleSubmit}>
<Box <Box
display='grid' display='grid'
@@ -107,7 +127,7 @@ const AdditionalInfo = () => {
value={form.values.firstName} value={form.values.firstName}
onChange={form.handleChange} onChange={form.handleChange}
onBlur={form.handleBlur} onBlur={form.handleBlur}
error={!!form.errors.firstName} error={form.touched.firstName && !!form.errors.firstName}
errorMessage={form.errors.firstName} errorMessage={form.errors.firstName}
/> />
<Input <Input
@@ -116,7 +136,7 @@ const AdditionalInfo = () => {
value={form.values.lastName} value={form.values.lastName}
onChange={form.handleChange} onChange={form.handleChange}
onBlur={form.handleBlur} onBlur={form.handleBlur}
error={!!form.errors.lastName} error={form.touched.lastName && !!form.errors.lastName}
errorMessage={form.errors.lastName} errorMessage={form.errors.lastName}
/> />
<Box <Box
@@ -127,13 +147,33 @@ const AdditionalInfo = () => {
<Select <Select
name='prefix' name='prefix'
label='Country Code' label='Country Code'
options={[ options={
{ value: '+216', label: '+216' }, countryCodes?.getCountryCode
{ value: '+213', label: '+213' }, ? [
]} {
value: '',
label: 'Choose',
},
...countryCodes.getCountryCode.map(
({ prefix, country }) => ({
value: prefix,
label: `+${prefix} (${country})`,
})
),
]
: [
{
value: '',
label: 'Choose',
},
{ value: '216', label: '+216' },
]
}
onChange={form.handleChange} onChange={form.handleChange}
onBlur={form.handleBlur} onBlur={form.handleBlur}
value={form.values.prefix} value={form.values.prefix}
error={form.touched.prefix && !!form.errors.prefix}
errorMessage={form.errors.prefix}
/> />
<Input <Input
name='number' name='number'
@@ -142,6 +182,8 @@ const AdditionalInfo = () => {
onChange={form.handleChange} onChange={form.handleChange}
onBlur={form.handleBlur} onBlur={form.handleBlur}
value={form.values.number} value={form.values.number}
error={form.touched.number && !!form.errors.number}
errorMessage={form.errors.number}
/> />
</Box> </Box>
<Input <Input
@@ -150,6 +192,8 @@ const AdditionalInfo = () => {
onChange={form.handleChange} onChange={form.handleChange}
onBlur={form.handleBlur} onBlur={form.handleBlur}
value={form.values.place} value={form.values.place}
error={form.touched.place && !!form.errors.place}
errorMessage={form.errors.place}
/> />
<Input <Input
name='city' name='city'
@@ -157,18 +201,44 @@ const AdditionalInfo = () => {
onChange={form.handleChange} onChange={form.handleChange}
onBlur={form.handleBlur} onBlur={form.handleBlur}
value={form.values.city} value={form.values.city}
error={form.touched.city && !!form.errors.city}
errorMessage={form.errors.city}
/> />
<Box <Box
display='grid' display='grid'
gridTemplateColumns='2fr 1fr' gridTemplateColumns='2fr 1fr'
columnGap='10px' columnGap='10px'
> >
<Input <Select
name='country' name='country'
label='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} onChange={form.handleChange}
onBlur={form.handleBlur} onBlur={form.handleBlur}
value={form.values.country} value={form.values.country}
error={form.touched.country && !!form.errors.country}
errorMessage={form.errors.country}
/> />
<Input <Input
name='zip' name='zip'
@@ -176,6 +246,8 @@ const AdditionalInfo = () => {
onChange={form.handleChange} onChange={form.handleChange}
onBlur={form.handleBlur} onBlur={form.handleBlur}
value={form.values.zip} value={form.values.zip}
error={form.touched.zip && !!form.errors.zip}
errorMessage={form.errors.zip}
/> />
</Box> </Box>
<Box marginTop='0.5rem'> <Box marginTop='0.5rem'>
@@ -192,6 +264,9 @@ const AdditionalInfo = () => {
{error && <Alert color='error' text={error} />} {error && <Alert color='error' text={error} />}
</Box> </Box>
</form> </form>
) : (
<Spinner fullScreen />
)}
</Box> </Box>
</Box> </Box>
</Wrapper> </Wrapper>
+195 -21
View File
@@ -1,9 +1,9 @@
import * as Yup from 'yup'; import * as Yup from 'yup';
import { useFormik } from 'formik'; import { useFormik } from 'formik';
import { useHistory } from 'react-router'; import { useHistory } from 'react-router';
import { useMutation, useReactiveVar } from '@apollo/client'; import { useMutation, useQuery, useReactiveVar } from '@apollo/client';
import { useState } from 'react'; import { useState } from 'react';
import { roleVar, userVar } from '../../graphql/state'; import { roleVar, tokenVar, userVar } from '../../graphql/state';
import { import {
Box, Box,
Button, Button,
@@ -12,6 +12,8 @@ import {
Input, Input,
Select, Select,
Alert, Alert,
Spinner,
Modal,
} from '../../components'; } from '../../components';
import { Wrapper } from './styles'; import { Wrapper } from './styles';
import { ArrowLeft, Profile, Security } from '../../assets'; import { ArrowLeft, Profile, Security } from '../../assets';
@@ -20,19 +22,33 @@ import {
UpdateUserPasswordMutation, UpdateUserPasswordMutation,
UpdateUserInfoMutationVariables, UpdateUserInfoMutationVariables,
UpdateUserPasswordMutationVariables, UpdateUserPasswordMutationVariables,
GetCountryCodesQuery,
GetCountryCodesQueryVariables,
DeleteUserMutation,
DeleteUserMutationVariables,
} from '../../graphql/types'; } 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 Settings = () => {
const history = useHistory(); const history = useHistory();
const role = useReactiveVar(roleVar); const role = useReactiveVar(roleVar);
const currentUser = useReactiveVar(userVar); const currentUser = useReactiveVar(userVar);
const { data: countryCodes, loading: countryCodesLoading } = useQuery<
GetCountryCodesQuery,
GetCountryCodesQueryVariables
>(GET_COUNTRY_CODES);
const [selectedSection, setSelectedSection] = useState< const [selectedSection, setSelectedSection] = useState<
'general' | 'security' 'general' | 'security'
>('general'); >('general');
const [error, setError] = useState<string>(''); const [error, setError] = useState<string>('');
const [success, setSuccess] = useState<boolean>(false); const [success, setSuccess] = useState<boolean>(false);
const [deleteAccountModal, setDeleteAccountModal] = useState<boolean>(false);
const [updateUserInfo, { loading: generalLoading }] = useMutation< const [updateUserInfo, { loading: generalLoading }] = useMutation<
UpdateUserInfoMutation, UpdateUserInfoMutation,
@@ -72,10 +88,13 @@ const Settings = () => {
firstName: Yup.string().required('First Name is required'), firstName: Yup.string().required('First Name is required'),
lastName: Yup.string().required('Last Name is required'), lastName: Yup.string().required('Last Name is required'),
prefix: Yup.string().required('Prefix 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'), place: Yup.string().required('Address is required'),
city: Yup.string().required('City is required'), city: Yup.string().required('City is required'),
country: Yup.string().required('Country 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: ({ onSubmit: ({
firstName, firstName,
@@ -122,16 +141,19 @@ const Settings = () => {
}, },
validationSchema: Yup.object().shape({ validationSchema: Yup.object().shape({
oldPassword: Yup.string() oldPassword: Yup.string()
.required('Password is required') .required('Old password is required')
.min(6, 'Password is 6 characters minimum'), .min(6, 'Old password is 6 characters minimum'),
newPassword: Yup.string() newPassword: Yup.string()
.required('New password is required')
.notOneOf( .notOneOf(
[Yup.ref('oldPassword')], [Yup.ref('oldPassword')],
'New password should not be old password' 'New password should not be old password'
) )
.required('New password is required') .required('New password is required')
.min(6, 'New password is 6 characters minimum'), .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')], [Yup.ref('newPassword')],
"Confirm new password doesn't match with new password" "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 ( return (
<Wrapper> <Wrapper>
<Box> <Box>
@@ -204,6 +263,8 @@ const Settings = () => {
)} )}
</Box> </Box>
{selectedSection === 'general' && ( {selectedSection === 'general' && (
<>
{!countryCodesLoading ? (
<form onSubmit={generalForm.handleSubmit}> <form onSubmit={generalForm.handleSubmit}>
<Box <Box
display='grid' display='grid'
@@ -214,19 +275,27 @@ const Settings = () => {
<Input <Input
name='firstName' name='firstName'
label='First Name' label='First Name'
color={role || 'client'}
value={generalForm.values.firstName} value={generalForm.values.firstName}
onChange={generalForm.handleChange} onChange={generalForm.handleChange}
onBlur={generalForm.handleBlur} onBlur={generalForm.handleBlur}
error={!!generalForm.errors.firstName} error={
generalForm.touched.firstName &&
!!generalForm.errors.firstName
}
errorMessage={generalForm.errors.firstName} errorMessage={generalForm.errors.firstName}
/> />
<Input <Input
name='lastName' name='lastName'
label='Last Name' label='Last Name'
color={role || 'client'}
value={generalForm.values.lastName} value={generalForm.values.lastName}
onChange={generalForm.handleChange} onChange={generalForm.handleChange}
onBlur={generalForm.handleBlur} onBlur={generalForm.handleBlur}
error={!!generalForm.errors.lastName} error={
generalForm.touched.lastName &&
!!generalForm.errors.lastName
}
errorMessage={generalForm.errors.lastName} errorMessage={generalForm.errors.lastName}
/> />
<Box <Box
@@ -237,55 +306,106 @@ const Settings = () => {
<Select <Select
name='prefix' name='prefix'
label='Country Code' label='Country Code'
options={[ color={role || 'client'}
{ value: '+216', label: '+216' }, options={
{ value: '+213', label: '+213' }, countryCodes?.getCountryCode
]} ? countryCodes.getCountryCode.map(
({ prefix, country }) => ({
value: prefix,
label: `+${prefix} (${country})`,
})
)
: [{ value: '216', label: '+216' }]
}
onChange={generalForm.handleChange} onChange={generalForm.handleChange}
onBlur={generalForm.handleBlur} onBlur={generalForm.handleBlur}
value={generalForm.values.prefix} value={generalForm.values.prefix}
select={generalForm.values.prefix}
error={
generalForm.touched.prefix &&
!!generalForm.errors.prefix
}
errorMessage={generalForm.errors.prefix}
/> />
<Input <Input
name='number' name='number'
type='tel' type='tel'
label='Phone' label='Phone'
color={role || 'client'}
onChange={generalForm.handleChange} onChange={generalForm.handleChange}
onBlur={generalForm.handleBlur} onBlur={generalForm.handleBlur}
value={generalForm.values.number} value={generalForm.values.number}
error={
generalForm.touched.number &&
!!generalForm.errors.number
}
errorMessage={generalForm.errors.number}
/> />
</Box> </Box>
<Input <Input
name='place' name='place'
label='Address' label='Address'
color={role || 'client'}
onChange={generalForm.handleChange} onChange={generalForm.handleChange}
onBlur={generalForm.handleBlur} onBlur={generalForm.handleBlur}
value={generalForm.values.place} value={generalForm.values.place}
error={
generalForm.touched.place && !!generalForm.errors.place
}
errorMessage={generalForm.errors.place}
/> />
<Input <Input
name='city' name='city'
label='City' label='City'
color={role || 'client'}
onChange={generalForm.handleChange} onChange={generalForm.handleChange}
onBlur={generalForm.handleBlur} onBlur={generalForm.handleBlur}
value={generalForm.values.city} value={generalForm.values.city}
error={
generalForm.touched.city && !!generalForm.errors.city
}
errorMessage={generalForm.errors.city}
/> />
<Box <Box
display='grid' display='grid'
gridTemplateColumns='2fr 1fr' gridTemplateColumns='2fr 1fr'
columnGap='10px' columnGap='10px'
> >
<Input <Select
name='country' name='country'
label='Country' label='Country'
color={role || 'client'}
options={
countryCodes?.getCountryCode
? countryCodes.getCountryCode.map(
({ country }) => ({
value: country,
label: country,
})
)
: [{ value: 'Tunisia', label: 'Tunisia' }]
}
onChange={generalForm.handleChange} onChange={generalForm.handleChange}
onBlur={generalForm.handleBlur} onBlur={generalForm.handleBlur}
value={generalForm.values.country} value={generalForm.values.country}
select={generalForm.values.country}
error={
generalForm.touched.country &&
!!generalForm.errors.country
}
errorMessage={generalForm.errors.country}
/> />
<Input <Input
name='zip' name='zip'
label='Zip Code' label='Zip Code'
color={role || 'client'}
onChange={generalForm.handleChange} onChange={generalForm.handleChange}
onBlur={generalForm.handleBlur} onBlur={generalForm.handleBlur}
value={generalForm.values.zip} value={generalForm.values.zip}
error={
generalForm.touched.zip && !!generalForm.errors.zip
}
errorMessage={generalForm.errors.zip}
/> />
</Box> </Box>
<Box <Box
@@ -296,7 +416,7 @@ const Settings = () => {
> >
<Button <Button
variant='primary-action' variant='primary-action'
color='client' color={role || 'client'}
text='Save' text='Save'
type='submit' type='submit'
loading={generalLoading} loading={generalLoading}
@@ -305,8 +425,40 @@ const Settings = () => {
</Box> </Box>
</Box> </Box>
</form> </form>
) : (
<Box display='grid' alignItems='center' justifyContent='center'>
<Spinner color={role || 'client'} />
</Box>
)}
</>
)} )}
{selectedSection === 'security' && ( {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}> <form onSubmit={securityForm.handleSubmit}>
<Box <Box
display='grid' display='grid'
@@ -317,42 +469,63 @@ const Settings = () => {
<Input <Input
name='oldPassword' name='oldPassword'
label='Old Password' label='Old Password'
color={role || 'client'}
type='password' type='password'
value={securityForm.values.oldPassword} value={securityForm.values.oldPassword}
onChange={securityForm.handleChange} onChange={securityForm.handleChange}
onBlur={securityForm.handleBlur} onBlur={securityForm.handleBlur}
error={!!securityForm.errors.oldPassword} error={
securityForm.touched.oldPassword &&
!!securityForm.errors.oldPassword
}
errorMessage={securityForm.errors.oldPassword} errorMessage={securityForm.errors.oldPassword}
/> />
<Input <Input
name='newPassword' name='newPassword'
label='New Password' label='New Password'
color={role || 'client'}
type='password' type='password'
value={securityForm.values.newPassword} value={securityForm.values.newPassword}
onChange={securityForm.handleChange} onChange={securityForm.handleChange}
onBlur={securityForm.handleBlur} onBlur={securityForm.handleBlur}
error={!!securityForm.errors.newPassword} error={
securityForm.touched.newPassword &&
!!securityForm.errors.newPassword
}
errorMessage={securityForm.errors.newPassword} errorMessage={securityForm.errors.newPassword}
/> />
<Input <Input
name='confirmNewPassword' name='confirmNewPassword'
label='Confirm New Password' label='Confirm New Password'
color={role || 'client'}
type='password' type='password'
value={securityForm.values.confirmNewPassword} value={securityForm.values.confirmNewPassword}
onChange={securityForm.handleChange} onChange={securityForm.handleChange}
onBlur={securityForm.handleBlur} onBlur={securityForm.handleBlur}
error={!!securityForm.errors.confirmNewPassword} error={
securityForm.touched.confirmNewPassword &&
!!securityForm.errors.confirmNewPassword
}
errorMessage={securityForm.errors.confirmNewPassword} errorMessage={securityForm.errors.confirmNewPassword}
/> />
<Box <Box
marginTop='0.5rem' marginTop='0.5rem'
display='flex' 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 <Button
variant='primary-action' variant='primary-action'
color='client' color={role || 'client'}
text='Save' text='Save'
type='submit' type='submit'
loading={securityLoading} loading={securityLoading}
@@ -361,6 +534,7 @@ const Settings = () => {
</Box> </Box>
</Box> </Box>
</form> </form>
</>
)} )}
</Box> </Box>
</Box> </Box>