Files
yaak/src-web/hooks/useHttpResponseEvents.ts
Gregory Schier bbcae34575 Fix race condition where streamed events could be lost
Events stream in via model_write listener while also being fetched
from the database. If the DB fetch completed before all events were
persisted, replaceModelsInStore would wipe out events that came in
via model_write.

Added mergeModelsInStore that adds fetched events without removing
existing ones. Applied to HTTP, gRPC, and WebSocket event hooks.
2026-01-11 07:42:04 -08:00

35 lines
1.1 KiB
TypeScript

import { invoke } from '@tauri-apps/api/core';
import type { HttpResponse, HttpResponseEvent } from '@yaakapp-internal/models';
import {
httpResponseEventsAtom,
mergeModelsInStore,
replaceModelsInStore,
} from '@yaakapp-internal/models';
import { useAtomValue } from 'jotai';
import { useEffect, useMemo } from 'react';
export function useHttpResponseEvents(response: HttpResponse | null) {
const allEvents = useAtomValue(httpResponseEventsAtom);
useEffect(() => {
if (response?.id == null) {
replaceModelsInStore('http_response_event', []);
return;
}
// Use merge instead of replace to preserve events that came in via model_write
// while we were fetching from the database
invoke<HttpResponseEvent[]>('cmd_get_http_response_events', { responseId: response.id }).then(
(events) => mergeModelsInStore('http_response_event', events),
);
}, [response?.id]);
// Filter events for the current response
const events = useMemo(
() => allEvents.filter((e) => e.responseId === response?.id),
[allEvents, response?.id],
);
return { data: events, error: null, isLoading: false };
}