import React, { useEffect, useState } from 'react'; import { useFormContext } from 'react-hook-form'; import { useValueSetServiceContext } from '../../../services'; interface CodedOption { system: string; code: string; display: string; } interface Props { name: string; list: boolean; valueSetUrl?: string; disabled?: boolean; } // Offers the one term named exactly as the note wrote it; a coded field is filed only once the clinician picks it. export const NoteTermOffer: React.FC = ({ name, list, valueSetUrl, disabled }) => { const { watch, setValue } = useFormContext(); const { fetchValueSetInternal } = useValueSetServiceContext() as { fetchValueSetInternal?: (url: string, grouped?: boolean, filter?: string) => Promise; }; const held = watch(name) as unknown; const first = (Array.isArray(held) ? held[0] : held) as { code?: string; display?: string } | undefined; const words = first && !first.code ? (first.display ?? '').trim() : ''; const [match, setMatch] = useState(); useEffect(() => { setMatch(undefined); if (!words || !valueSetUrl || !fetchValueSetInternal) return; let active = true; fetchValueSetInternal(valueSetUrl, false, words) .then((options) => { if (!active || !Array.isArray(options)) return; const exact = (options as CodedOption[]) .filter((option) => option.code && option.display?.trim().toLowerCase() === words.toLowerCase()); if (exact.length === 1) setMatch(exact[0]); }) .catch(() => undefined); return () => { active = false; }; }, [words, valueSetUrl, fetchValueSetInternal]); if (!match || !words) return null; return ( ); }; export default NoteTermOffer;