MCPcopy Create free account
hub / github.com/TryCatchLearn/Restore-v2 / ProductForm

Function ProductForm

client/src/features/admin/ProductForm.tsx:22–132  ·  view source on GitHub ↗
({setEditMode, product, refetch, setSelectedProduct}: Props)

Source from the content-addressed store, hash-verified

20}
21
22export default function ProductForm({setEditMode, product, refetch, setSelectedProduct}: Props) {
23 const {control, handleSubmit, watch, reset, setError, formState: {isSubmitting}} = useForm<CreateProductSchema>({
24 mode: 'onTouched',
25 resolver: zodResolver(createProductSchema)
26 })
27 const watchFile = watch('file');
28 const {data} = useFetchFiltersQuery();
29 const [createProduct] = useCreateProductMutation();
30 const [updateProduct] = useUpdateProductMutation();
31
32 useEffect(() => {
33 if (product) reset(product);
34
35 return () => {
36 if (watchFile) URL.revokeObjectURL(watchFile.preview)
37 }
38 }, [product, reset, watchFile]);
39
40 const createFormData = (items: FieldValues) => {
41 const formData = new FormData();
42 for (const key in items) {
43 formData.append(key, items[key])
44 }
45
46 return formData;
47 }
48
49 const onSubmit = async (data: CreateProductSchema) => {
50 try {
51 const formData = createFormData(data);
52
53 if (watchFile) formData.append('file', watchFile);
54
55 if (product) await updateProduct({id: product.id, data: formData}).unwrap();
56 else await createProduct(formData).unwrap();
57 setEditMode(false);
58 setSelectedProduct(null);
59 refetch();
60 } catch (error) {
61 console.log(error);
62 handleApiError<CreateProductSchema>(error, setError,
63 ['brand', 'description', 'file', 'name', 'pictureUrl',
64 'price', 'quantityInStock', 'type']);
65 }
66 }
67
68 return (
69 <Box component={Paper} sx={{p: 4, maxWidth: 'lg', mx: 'auto'}}>
70 <Typography variant="h4" sx={{mb: 4}}>
71 Product details
72 </Typography>
73 <form onSubmit={handleSubmit(onSubmit)}>
74 <Grid2 container spacing={3}>
75 <Grid2 size={12}>
76 <AppTextInput control={control} name="name" label='Product name' />
77 </Grid2>
78 <Grid2 size={6}>
79 {data?.brands &&

Callers

nothing calls this directly

Calls 1

resetFunction · 0.85

Tested by

no test coverage detected