summaryrefslogtreecommitdiff
path: root/src/hooks/useOptions.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/hooks/useOptions.ts')
-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;