summaryrefslogtreecommitdiff
path: root/src/hooks
diff options
context:
space:
mode:
authoreug-vs <eug-vs@keemail.me>2021-03-14 13:27:01 +0300
committereug-vs <eug-vs@keemail.me>2021-03-14 13:27:01 +0300
commit31a196a76513df809ee91427129926370de551ba (patch)
tree9ce14806fd8da9393de27ab3747a700546e6bd86 /src/hooks
parent887688bb93b56cf2bd6ec42230912ff7f0513a1d (diff)
downloadcommercel-ui-31a196a76513df809ee91427129926370de551ba.tar.gz
feat: add useOptions hook
Diffstat (limited to 'src/hooks')
-rw-r--r--src/hooks/useOptions.ts28
1 files changed, 28 insertions, 0 deletions
diff --git a/src/hooks/useOptions.ts b/src/hooks/useOptions.ts
new file mode 100644
index 0000000..de8fc95
--- /dev/null
+++ b/src/hooks/useOptions.ts
@@ -0,0 +1,28 @@
+import { useEffect } from 'react';
+import { Option } from '../components/Select';
+import hooks from './useAPIClient';
+
+// Load service entities and map them into select options
+// setting the default value in formik
+const useOptions = (
+ service: string,
+ field: string,
+ values: Record<string, any>,
+ setFieldValue: (any) => void,
+ mapper = item => ({ key: item._id, label: item.name }),
+): Option[] => {
+ const { data: items } = hooks[service].useList();
+
+ const options = items?.map(mapper);
+
+ useEffect(() => {
+ if (items?.length && !values[field]) {
+ setFieldValue(field, items[0]._id);
+ }
+ }, [items, setFieldValue]);
+
+ return options;
+};
+
+
+export default useOptions;