summaryrefslogtreecommitdiff
path: root/src/containers/Service/ServiceForm.tsx
blob: 273f5bdd1619b0114c6f16856c512b0dfa96b303 (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
import React, { useContext } from 'react';
import { useParams, useHistory } from 'react-router-dom';
import { Formik } from 'formik';
import Page, { Action } from '../Page';
import hooks from '../../hooks/useAPIClient';
import { post, patch } from '../../requests';
import ServiceContext from './ServiceContext';

interface Params {
  id: string;
}

const actions: Action[] = [
  { name: 'Назад', variant: 'outlined', route: '..' },
  { name: 'Сохранить', type: 'submit', form: 'form' },
];

const ServiceForm: React.FC = () => {
  const service = useContext(ServiceContext);
  const history = useHistory();
  const { id } = useParams<Params>();
  const { data: item } = hooks[service.route].useItem(id);

  const onSubmit = (values: any) => {
    const promise = id
      ? patch(`/${service.route}/${id}`, values)
      : post(`/${service.route}`, values);
    return promise.then(() => history.push(`/${service.route}`));
  };

  return (
    <Page title={id ? item?.name : `Новый ${service.nameSingular}`} actions={actions}>
      {(!id || item) && (
        <Formik
          initialValues={item || { name: '', debt: '', vatId: '' }}
          onSubmit={onSubmit}
        >
          <service.Form />
        </Formik>
      )}
    </Page>
  );
};

export default ServiceForm;