From 2305464999fdccdb809ce425cda8346ddc3df493 Mon Sep 17 00:00:00 2001 From: eug-vs Date: Wed, 17 Mar 2021 03:46:21 +0300 Subject: feat: adapt useOptions to the new logic --- .eslintrc.json | 1 + src/containers/WaybillForm.tsx | 7 +++++-- src/hooks/useOptions.ts | 12 +++++++----- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/.eslintrc.json b/.eslintrc.json index 8fbc76e..b780736 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -16,6 +16,7 @@ "arrow-parens": [2, "as-needed"], "import/extensions": ["error", { "ts": "never", "tsx": "never" }], "arrow-body-style": 0, + "curly": 0, "no-underscore-dangle": 0, "no-cond-assign": 0, "no-nested-ternary": 0, diff --git a/src/containers/WaybillForm.tsx b/src/containers/WaybillForm.tsx index 2167d17..1297a0f 100644 --- a/src/containers/WaybillForm.tsx +++ b/src/containers/WaybillForm.tsx @@ -7,13 +7,16 @@ import Select from '../components/Select'; import Paper from '../components/Paper'; import useOptions from '../hooks/useOptions'; + const WaybillForm: React.FC = ({ setFieldValue, values }) => { const [recordsNumber, setRecordsNumber] = useState(values.records.length); const handleAddRecord = () => setRecordsNumber(v => v + 1); - const contractorOptions = useOptions('contractors', 'contractorId', values, setFieldValue); - const productOptions = useOptions('products', 'productId', values, setFieldValue); + const productInitFields = _.times(recordsNumber).map(index => `records.${index}.productId`); + + const contractorOptions = useOptions('contractors', ['contractorId'], values, setFieldValue); + const productOptions = useOptions('products', productInitFields, values, setFieldValue); return (
diff --git a/src/hooks/useOptions.ts b/src/hooks/useOptions.ts index de8fc95..2a5aee6 100644 --- a/src/hooks/useOptions.ts +++ b/src/hooks/useOptions.ts @@ -1,4 +1,5 @@ import { useEffect } from 'react'; +import _ from 'lodash'; import { Option } from '../components/Select'; import hooks from './useAPIClient'; @@ -6,7 +7,7 @@ import hooks from './useAPIClient'; // setting the default value in formik const useOptions = ( service: string, - field: string, + fields: string[], values: Record, setFieldValue: (any) => void, mapper = item => ({ key: item._id, label: item.name }), @@ -16,10 +17,11 @@ const useOptions = ( const options = items?.map(mapper); useEffect(() => { - if (items?.length && !values[field]) { - setFieldValue(field, items[0]._id); - } - }, [items, setFieldValue]); + // Initialize all empty fields + if (items?.length) fields.forEach(field => { + if (!_.get(values, field)) setFieldValue(field, items[0]._id); + }); + }, [items, values, setFieldValue]); return options; }; -- cgit v1.2.3