You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

use-build-form-refs.ts 1.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { isEmpty } from 'lodash';
  2. import { useCallback, useEffect, useRef } from 'react';
  3. export function useBuildFormRefs(chatBoxIds: string[]) {
  4. const formRefs = useRef<Record<string, { getFormData: () => any }>>({});
  5. const setFormRef = (id: string) => (ref: { getFormData: () => any }) => {
  6. formRefs.current[id] = ref;
  7. };
  8. const cleanupFormRefs = useCallback(() => {
  9. const currentIds = new Set(chatBoxIds);
  10. Object.keys(formRefs.current).forEach((id) => {
  11. if (!currentIds.has(id)) {
  12. delete formRefs.current[id];
  13. }
  14. });
  15. }, [chatBoxIds]);
  16. const getLLMConfigById = useCallback(
  17. (chatBoxId?: string) => {
  18. const llmConfig = chatBoxId
  19. ? formRefs.current[chatBoxId].getFormData()
  20. : {};
  21. return llmConfig;
  22. },
  23. [formRefs],
  24. );
  25. const isLLMConfigEmpty = useCallback(
  26. (chatBoxId?: string) => {
  27. return isEmpty(getLLMConfigById(chatBoxId)?.llm_id);
  28. },
  29. [getLLMConfigById],
  30. );
  31. useEffect(() => {
  32. cleanupFormRefs();
  33. }, [cleanupFormRefs]);
  34. return {
  35. formRefs,
  36. setFormRef,
  37. getLLMConfigById,
  38. isLLMConfigEmpty,
  39. };
  40. }