import { useEffect } from 'react'; import { Schedule } from 'fhir/r4'; import { useScheduleServiceContext, useWebSocketServiceContext } from '../services'; export const useFhirScheduleBroadcast = () => { const { subscribe, unsubscribe } = useWebSocketServiceContext(); const { setSchedulesList } = useScheduleServiceContext(); useEffect(() => { const handleScheduleEvent = (cloudEvent: any) => { const schedule: Schedule = cloudEvent.data; const eventType = cloudEvent.type; switch (eventType) { case 'com.akashichealthrecords.fhir.schedule.created': // The list has two writers: this broadcast, and the service's own refetch after a write // (several of which POLL until the new id appears). Refetch first and the list already holds // the record, so an unconditional append put a SECOND copy of it on screen - observed on a // patient's questionnaire answers, where one submission rendered as two completed forms. // Keeping the broadcast's copy rather than skipping: its body is at least as fresh. setSchedulesList(prev => prev.some(p => p.id === schedule.id) ? prev.map(p => p.id === schedule.id ? schedule : p) : [...prev, schedule] ); break; case 'com.akashichealthrecords.fhir.schedule.updated': setSchedulesList(prev => prev.map(p => p.id === schedule.id ? schedule : p)); break; case 'com.akashichealthrecords.fhir.schedule.deleted': setSchedulesList(prev => prev.filter(p => p.id !== schedule.id)); break; } }; subscribe('com.akashichealthrecords.fhir.schedule.created', handleScheduleEvent); subscribe('com.akashichealthrecords.fhir.schedule.updated', handleScheduleEvent); subscribe('com.akashichealthrecords.fhir.schedule.deleted', handleScheduleEvent); return () => { unsubscribe('com.akashichealthrecords.fhir.schedule.created', handleScheduleEvent); unsubscribe('com.akashichealthrecords.fhir.schedule.updated', handleScheduleEvent); unsubscribe('com.akashichealthrecords.fhir.schedule.deleted', handleScheduleEvent); }; }, [subscribe, unsubscribe]); };