hooks.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import {editDictionary, getDictionaryInfo} from '@apis';
  2. import {yupResolver} from '@hookform/resolvers/yup';
  3. import {useQueryDataInfo} from '@hooks';
  4. import {useMutation} from '@tanstack/react-query';
  5. import {message} from 'antd';
  6. import {useEffect} from 'react';
  7. import {useForm, useFormContext} from 'react-hook-form';
  8. import {number, object, string} from 'yup';
  9. type FormState = {
  10. goodsType: string,
  11. goodsSize: number,
  12. goodsMixin: string,
  13. goodsRecommend: string,
  14. };
  15. const validate = object({
  16. goodsType: string().required('请选择物料类型'),
  17. goodsSize: number().typeError('请输入数字')
  18. .min(1, '不能小于1个').required('请输入物料存储容量'),
  19. goodsMixin: string().required('请选择是否混合存储'),
  20. goodsRecommend: string().required('请选择是否推荐库位'),
  21. });
  22. export function useFormState(
  23. {visible, id, onClose, onFetch}:
  24. {onClose: () => void, onFetch: () => void, visible: boolean, id: string},
  25. ) {
  26. const formInstance = useForm<FormState>({
  27. defaultValues: {goodsType: '', goodsSize: 1, goodsMixin: '', goodsRecommend: ''},
  28. resolver: yupResolver(validate),
  29. });
  30. const {clearErrors, handleSubmit} = formInstance;
  31. useEffect(function() {
  32. visible && clearErrors();
  33. }, [visible, clearErrors]);
  34. const {isLoading, mutate} = useMutation({
  35. mutationFn: editDictionary,
  36. onSuccess({msg}) {
  37. if (msg === '200') {
  38. onClose();
  39. onFetch();
  40. message.success('修改成功');
  41. }
  42. },
  43. });
  44. const onSubmit = handleSubmit(function({goodsMixin, goodsSize, goodsType, goodsRecommend}) {
  45. mutate({
  46. isNotDisable: goodsMixin,
  47. size: String(goodsSize),
  48. id,
  49. materialType: goodsType,
  50. isRecommend: goodsRecommend,
  51. });
  52. });
  53. return [{formInstance, isLoading}, {onSubmit}] as const;
  54. }
  55. export function useControl() {
  56. const {control} = useFormContext<FormState>();
  57. return control;
  58. }
  59. export function useWatchId(id: string) {
  60. const {setValue} = useFormContext<FormState>();
  61. const data = useQueryDataInfo({
  62. queryFn: getDictionaryInfo,
  63. params: ['物料字典', id],
  64. enabled: Boolean(id),
  65. });
  66. useEffect(function() {
  67. setValue('goodsType', data?.wllbClass ?? '');
  68. setValue('goodsSize', Number(data?.size ?? '1'));
  69. setValue('goodsMixin', data?.isNotDisable ?? '');
  70. setValue('goodsRecommend', data?.isRecommend ?? '');
  71. }, [data, setValue]);
  72. }