diff --git a/Lab5/data.json b/Lab5/data.json index e7b050e..493caec 100644 --- a/Lab5/data.json +++ b/Lab5/data.json @@ -3,7 +3,8 @@ { "id": 0, "login": "dyctator", - "password": "12345" + "password": "12345", + "role": "user" } ], "directions": [ diff --git a/Lab5/src/components/logins/hooks/DataItemHook.js b/Lab5/src/components/logins/hooks/DataItemHook.js new file mode 100644 index 0000000..0d14246 --- /dev/null +++ b/Lab5/src/components/logins/hooks/DataItemHook.js @@ -0,0 +1,33 @@ +import { useEffect, useState } from 'react'; +import EntrysDataApiService from '../service/EntrysDataApiService'; + +const useEntysDataItem = (id) => { + const emptyItem = { + id: '', + login: '', + password: '', + role: '', + }; + const [item, setItem] = useState({ ...emptyItem }); + + const getItem = async (itemId = undefined) => { + if (itemId && itemId > 0) { + const data = await EntrysDataApiService.get(itemId); + setItem(data); + } else { + setItem({ ...emptyItem }); + } + }; + + useEffect(() => { + getItem(id); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [id]); + + return { + item, + setItem, + }; +}; + +export default useEntysDataItem; diff --git a/Lab5/src/components/logins/hooks/EntrysDataItemHook.js b/Lab5/src/components/logins/hooks/EntrysDataItemHook.js new file mode 100644 index 0000000..68f8d96 --- /dev/null +++ b/Lab5/src/components/logins/hooks/EntrysDataItemHook.js @@ -0,0 +1,65 @@ +import { useState } from 'react'; +import EntrysDataApiService from '../service/EntrysDataApiService'; +import useEntysDataItem from './DataItemHook'; + +const useLinesItemForm = (id, linesChangeHandle) => { + const { item, setItem } = useEntysDataItem(id); + + const [modified, setModified] = useState(false); + + const [validated, setValidated] = useState(false); + + const resetValidity = () => { + setValidated(false); + }; + + const getLineObject = (formData) => { + const Login = formData.login.toString(); + const Password = formData.password.toString(); + const Role = formData.role.toString(); + return { + login: Login, + password: Password, + role: Role, + }; + }; + + const handleChange = (event) => { + const inputName = event.target.name; + const inputValue = event.target.type === 'checkbox' ? event.target.checked : event.target.value; + setItem({ + ...item, + [inputName]: inputValue, + }); + }; + + const handleSubmit = async (event) => { + const form = event.currentTarget; + event.preventDefault(); + event.stopPropagation(); + const body = getLineObject(item); + if (form.checkValidity()) { + if (id === undefined) { + await EntrysDataApiService.create(body); + } else { + await EntrysDataApiService.update(id, body); + } + if (linesChangeHandle) linesChangeHandle(); + setModified(true); + return true; + } + setValidated(true); + return false; + }; + + return { + item, + validated, + handleSubmit, + handleChange, + resetValidity, + isModified: modified, + }; +}; + +export default useLinesItemForm;