From 455cf10c5f3fcdbec274cf200c1706c727141cfb Mon Sep 17 00:00:00 2001 From: Nate Kelley Date: Mon, 14 Jul 2025 12:39:02 -0600 Subject: [PATCH] create a stream dynamically on change --- apps/web/src/api/buster-electric/instances.ts | 13 ++++++++----- apps/web/src/api/buster-electric/messages/hooks.ts | 8 ++++---- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/apps/web/src/api/buster-electric/instances.ts b/apps/web/src/api/buster-electric/instances.ts index 7e0d94798..aedbaf68a 100644 --- a/apps/web/src/api/buster-electric/instances.ts +++ b/apps/web/src/api/buster-electric/instances.ts @@ -9,6 +9,7 @@ import { import { ELECTRIC_BASE_URL } from './config'; import { useSupabaseContext } from '@/context/Supabase'; import { useEffect, useMemo, useRef } from 'react'; +import { useMemoizedFn } from '../../hooks'; export type ElectricShapeOptions = Row> = Omit< Parameters>[0], @@ -60,7 +61,7 @@ export const useShapeStream = = Row>( const memoParams = useMemo(() => params, [JSON.stringify(params)]); const abortRef = useRef(); - const stream = useMemo(() => { + const createStream = useMemoizedFn(() => { abortRef.current?.abort(); const controller = new AbortController(); abortRef.current = controller; @@ -72,13 +73,15 @@ export const useShapeStream = = Row>( ...opts, signal: controller.signal }); - }, [memoParams, accessToken]); + }); useEffect(() => { if (!subscribe) { return; } + const stream = createStream(); + let hasSyncedInitial = false; const handler = (messages: Message[]) => { @@ -107,13 +110,13 @@ export const useShapeStream = = Row>( }; function tearDown() { - unsubscribe(); + unsubscribe?.(); abortRef.current?.abort(); } }, [ - stream, - subscribe, memoParams, + accessToken, + subscribe, operations.join(','), // primitive dep onUpdate, shouldUnsubscribe diff --git a/apps/web/src/api/buster-electric/messages/hooks.ts b/apps/web/src/api/buster-electric/messages/hooks.ts index facef37ff..b3a039d2b 100644 --- a/apps/web/src/api/buster-electric/messages/hooks.ts +++ b/apps/web/src/api/buster-electric/messages/hooks.ts @@ -33,14 +33,14 @@ export const useTrackAndUpdateMessageChanges = ( ) => { const { onUpdateChatMessage, onUpdateChat } = useChatUpdate(); const getChatMemoized = useGetChatMemoized(); - + + const subscribe = !!chatId && !!messageId && messageId !== 'undefined'; + const shape = useMemo( () => messageShape({ chatId: chatId || '', messageId }), [chatId, messageId] ); - const subscribe = !!chatId && !!messageId && messageId !== 'undefined'; - return useShapeStream( shape, updateOperations, @@ -61,7 +61,7 @@ export const useTrackAndUpdateMessageChanges = ( } if (iChatMessage.is_completed) { - prefetchGetListChats() + prefetchGetListChats(); } } callback?.(iChatMessage);