import * as Yup from 'yup'; import { useFormik } from 'formik'; import { useMutation, useQuery, useReactiveVar } from '@apollo/client'; import { useState } from 'react'; import { Redirect, useHistory } from 'react-router'; import { roleVar } from '../../graphql/state'; import { Add, Delete, Edit, Empty } from '../../assets'; import { Box, Button, Spinner, Text, Modal, Input, Alert, } from '../../components'; import { Wrapper } from './styles'; import { DeleteUserMutation, DeleteUserMutationVariables, GetAllUsersQuery, GetAllUsersQueryVariables, UserResponseModel, } from '../../graphql/types'; import { GET_ALL_USERS } from '../../graphql/admin.api'; import { DELETE_USER } from '../../graphql/auth.api'; const Clients = () => { const role = useReactiveVar(roleVar); const history = useHistory(); const [clients, setClients] = useState>(); const [userToDelete, setUserToDelete] = useState(); const [error, setError] = useState(''); const [deleteAccountModal, setDeleteAccountModal] = useState(false); const { loading } = useQuery( GET_ALL_USERS, { onCompleted({ getAllUsers }) { setClients(getAllUsers.filter((user) => user.role === 'Client')); }, } ); const [deleteUser] = useMutation< DeleteUserMutation, DeleteUserMutationVariables >(DELETE_USER, { onCompleted() { setClients(clients?.filter((client) => client.id !== userToDelete?.id)); setUserToDelete(undefined); setDeleteAccountModal(false); }, 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: userToDelete?.id!, password } }); } finally { resetForm(); } }, }); return role === 'admin' ? ( <> {!loading ? ( <> {deleteAccountModal && ( setDeleteAccountModal(false)} onConfirm={deleteAccountForm.handleSubmit} > )} {clients && clients.length > 0 ? ( Clients {error && ( )}