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
|
import React, { useContext } from 'react';
import { useParams, useHistory } from 'react-router-dom';
import { Formik } from 'formik';
import _ from 'lodash';
import Page, { Action } from '../Page';
import hooks from '../../hooks/useAPIClient';
import { post, patch, del } from '../../requests';
import ServiceContext from './ServiceContext';
interface Params {
id: string;
}
const ServiceItem: React.FC = () => {
const service = useContext(ServiceContext);
const history = useHistory();
const { id } = useParams<Params>();
const { data: item, mutate } = hooks[service.route].useItem(id);
const handleDelete = () => del(`/${service.route}/${id}`)
.then(() => history.push(`/${service.route}`));
const onSubmit = (values: any) => {
const promise = id
? patch(`/${service.route}/${id}`, values)
: post(`/${service.route}`, values);
return promise.then(response => {
mutate(response.data);
history.push(`/${service.route}`);
});
};
const actions: Action[] = [
{ name: 'Назад', variant: 'outlined', onClick: history.goBack },
{ name: 'Удалить', variant: 'outlined', onClick: handleDelete },
{ name: 'Сохранить', type: 'submit', form: 'form' },
];
return (
<Page
title={id ? item?.name : `Новый ${service.nameSingular}`}
actions={actions}
className="grid lg:grid-cols-2"
>
{(!id || item) && (
<Formik
initialValues={_.defaults(item, service.default)}
onSubmit={onSubmit}
children={service.Form}
/>
)}
{item && service.Panel && <service.Panel item={item} mutate={mutate} />}
</Page>
);
};
export default ServiceItem;
|