summaryrefslogtreecommitdiff
path: root/src/containers/Service/ServiceItem.tsx
blob: f833227ecd8ccd80b4f59efba0ba452999e06d0a (plain)
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
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 useQuery from '../../hooks/useQuery';
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 query = useQuery();
  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[] = _.compact([
    { name: 'Назад', variant: 'outlined', onClick: history.goBack },
    id && { 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, query, service.default)}
          onSubmit={onSubmit}
          children={service.Form}
        />
      )}
      {item && service.Panel && <service.Panel item={item} mutate={mutate} />}
    </Page>
  );
};

export default ServiceItem;