From 865b41114060765308d560181f4996c0aa7a3e74 Mon Sep 17 00:00:00 2001 From: eug-vs Date: Fri, 26 Mar 2021 01:06:44 +0300 Subject: refactor: move Service to lib/ --- src/lib/ServiceItem.tsx | 59 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 src/lib/ServiceItem.tsx (limited to 'src/lib/ServiceItem.tsx') diff --git a/src/lib/ServiceItem.tsx b/src/lib/ServiceItem.tsx new file mode 100644 index 0000000..6a0a99b --- /dev/null +++ b/src/lib/ServiceItem.tsx @@ -0,0 +1,59 @@ +import React, { useContext } from 'react'; +import { useParams, useHistory } from 'react-router-dom'; +import { Formik } from 'formik'; +import _ from 'lodash'; +import Page from '../containers/Page'; +import hooks from '../hooks/useAPIClient'; +import useQuery from '../hooks/useQuery'; +import { post, patch, del } from '../requests'; +import ServiceContext, { Action } from './ServiceContext'; + +interface Params { + id: string; +} + +const ServiceItem: React.FC = () => { + const service = useContext(ServiceContext); + const history = useHistory(); + const query = useQuery(); + const { id } = useParams(); + 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 ( + + {(!id || item) && ( + + )} + {item && service.Panel && } + + ); +}; + +export default ServiceItem; -- cgit v1.2.3