summaryrefslogtreecommitdiff
path: root/src/hooks/useOptions.ts
blob: de8fc95cbf3939dd30eeb7f2b27b0f36abf7d6c6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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;