/
SellerFrom.hook.ts
92 lines (85 loc) · 2.38 KB
/
SellerFrom.hook.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import { useMutation } from '@tanstack/react-query';
import React, { FormEvent, RefObject } from 'react';
import { AddSellerType, SellerForm } from '../Seller.hook';
export type ErrorFormType = {
hasError: boolean;
message: string;
};
export const useForm = (
addSeller: AddSellerType
): {
nameRef: RefObject<HTMLInputElement>;
passwordRef: RefObject<HTMLInputElement>;
urlRef: RefObject<HTMLInputElement>;
handleSubmit: (event: FormEvent) => void;
errorForm: ErrorFormType;
} => {
const nameRef: RefObject<HTMLInputElement> = React.useRef(null);
const passwordRef: RefObject<HTMLInputElement> = React.useRef(null);
const urlRef: RefObject<HTMLInputElement> = React.useRef(null);
const initErrorFormState = {
hasError: false,
message: '',
};
const [errorForm, setErrorForm] =
React.useState<ErrorFormType>(initErrorFormState);
const addSellerMutation = useMutation(async (newSeller: SellerForm) =>
fetch('/seller', {
method: 'POST',
body: new URLSearchParams(newSeller),
})
);
const handleSubmit = (event: FormEvent): void => {
const name = nameRef.current?.value;
const password = passwordRef.current?.value;
const url = urlRef.current?.value;
setErrorForm(initErrorFormState);
event.preventDefault();
if (!name) {
setErrorForm({
hasError: true,
message: 'name is required',
});
return;
}
if (!password) {
setErrorForm({
hasError: true,
message: 'password is required',
});
return;
}
if (!url) {
setErrorForm({
hasError: true,
message: 'url is required',
});
return;
}
addSellerMutation.mutate(
{ name, password, url },
{
onSuccess: async (response) => {
if (!response.ok) {
setErrorForm({
hasError: true,
message: 'An error occurred during registration',
});
} else {
addSeller({ name, cash: 0, online: true });
}
},
onError: async (err) => {
setErrorForm({
hasError: true,
message: `An error occured during registration: ${err}`,
});
},
}
);
nameRef.current.value = '';
urlRef.current.value = '';
passwordRef.current.value = '';
};
return { nameRef, passwordRef, urlRef, handleSubmit, errorForm };
};