import React, { useState } from 'react'; import { observer } from 'mobx-react'; import { SubmitHandler, useForm } from 'react-hook-form'; import { MdSave } from 'react-icons/md'; import { Text, Input, Button } from '@chakra-ui/react'; import { Box, Heading, Stack } from '@chakra-ui/layout'; import { FormControl, FormHelperText } from '@chakra-ui/form-control'; import { yupResolver } from '@hookform/resolvers/yup'; /** * Types */ import { IUserContacts } from '@educt/interfaces'; /** * Hooks */ import { useToast } from '@chakra-ui/toast'; import { useRootStore } from '@educt/hooks/useRootStore'; import { useErrorHandler } from 'react-error-boundary'; /** * Schema */ import UpdateUserContactsSchema from './UpdateUserContactsForm.validator'; type UpdateUserContactsInputType = { phone_number: string | null; twitter_id: string | null; telegram_id: string | null; vk_id: string | null; }; type UpdateUserContactsFormPropsType = { contacts: IUserContacts | null; }; const UpdateUserContactsForm: React.FC = ({ contacts }) => { const { register, formState: { errors, isDirty }, handleSubmit, reset, } = useForm({ resolver: yupResolver(UpdateUserContactsSchema), defaultValues: { phone_number: contacts && (contacts.phone_number ?? ''), twitter_id: contacts && (contacts.twitter_id?.replace(/^/, '@') ?? ''), telegram_id: contacts && (contacts.telegram_id?.replace(/^/, '@') ?? ''), vk_id: contacts && (contacts.vk_id ?? ''), }, }); const [isLoading, setIsLoading] = useState(false); const { userStore } = useRootStore(); const toast = useToast(); const handleError = useErrorHandler(); /** * Sumbit form handler */ const onSubmit: SubmitHandler = async data => { try { setIsLoading(true); await userStore.updateCurrentUserContacts(data); toast({ title: 'Contacts saved!', status: 'info' }); reset({ phone_number: data.phone_number ?? '', twitter_id: data.twitter_id ?? '', telegram_id: data.telegram_id ?? '', vk_id: data.vk_id ?? '', }); setIsLoading(false); } catch (error: any) { if (error.response) { switch (error.response.status) { case 422: toast({ title: error.response.data.errors[0].message, status: 'error', duration: 2000 }); break; default: handleError(error); } } else { handleError(error); } } finally { setIsLoading(false); } }; return (
Phone number with country code {errors.phone_number?.message} Twitter {errors.twitter_id?.message} Telegram {errors.telegram_id?.message} VKontakte {errors.vk_id?.message}
); }; export default observer(UpdateUserContactsForm);