import { useEffect } from 'react'; import _ from 'lodash'; 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, fields: string[], values: Record, setFieldValue: (any) => void, mapper = item => ({ key: item._id, label: item.name }), ): Option[] => { const { data: items } = hooks[service].useList(); const options = items?.map(mapper); useEffect(() => { // Initialize all empty fields if (items?.length) fields.forEach(field => { if (!_.get(values, field)) setFieldValue(field, items[0]._id); }); }, [items, values, setFieldValue]); return options; }; export default useOptions;