From 2f0bc40cfd5591ab05ebbc5147f912b2fd415172 Mon Sep 17 00:00:00 2001 From: Nate Kelley Date: Sat, 15 Feb 2025 20:45:11 -0700 Subject: [PATCH] query emit on --- .../useSocketQueryEmitOn.tsx | 24 +++++++++++++++---- .../BusterMetricsIndividualProvider.tsx | 1 - 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/web/src/api/buster_socket_query/useSocketQueryEmitOn.tsx b/web/src/api/buster_socket_query/useSocketQueryEmitOn.tsx index 42ecb96ba..f75e4b4fe 100644 --- a/web/src/api/buster_socket_query/useSocketQueryEmitOn.tsx +++ b/web/src/api/buster_socket_query/useSocketQueryEmitOn.tsx @@ -1,5 +1,10 @@ import type { BusterSocketResponseRoute, BusterSocketRequest } from '@/api/buster_socket'; -import type { QueryKey, UseQueryOptions } from '@tanstack/react-query'; +import { + queryOptions, + useQueryClient, + type QueryKey, + type UseQueryOptions +} from '@tanstack/react-query'; import type { InferBusterSocketResponseData } from './types'; import { useBusterWebSocket } from '@/context/BusterWebSocket'; import { useEffect } from 'react'; @@ -20,20 +25,29 @@ export const useSocketQueryEmitOn = < | null, enabledTriggerProp?: boolean | string ) => { + const queryClient = useQueryClient(); const busterSocket = useBusterWebSocket(); const enabledTrigger = enabledTriggerProp ?? true; const emitQueryFn = useMemoizedFn(async () => { - busterSocket.emit(socketRequest); + const queryState = queryClient.getQueryState(options.queryKey); + if (!queryState) { + busterSocket.emit(socketRequest); + } }); + const queryResult = useSocketQueryOn(socketResponse, options, callback); + useEffect(() => { - if (enabledTrigger) { + const queryState = queryClient.getQueryState(options.queryKey); + const staleTime = (options.staleTime as number) ?? 0; + const isStale = + !queryState?.dataUpdatedAt || Date.now() - queryState.dataUpdatedAt >= staleTime; + + if (enabledTrigger && (isStale || !queryState)) { emitQueryFn(); } }, [enabledTrigger]); - const queryResult = useSocketQueryOn(socketResponse, options, callback); - return { ...queryResult, refetch: emitQueryFn }; }; diff --git a/web/src/context/Metrics/BusterMetricsIndividualProvider/BusterMetricsIndividualProvider.tsx b/web/src/context/Metrics/BusterMetricsIndividualProvider/BusterMetricsIndividualProvider.tsx index d1245578d..42c6153ce 100644 --- a/web/src/context/Metrics/BusterMetricsIndividualProvider/BusterMetricsIndividualProvider.tsx +++ b/web/src/context/Metrics/BusterMetricsIndividualProvider/BusterMetricsIndividualProvider.tsx @@ -17,7 +17,6 @@ import { useQueryClient } from '@tanstack/react-query'; import { queryKeys } from '@/api/query_keys'; export const useBusterMetricsIndividual = () => { - const [isPending, startTransition] = useTransition(); const { metricId: selectedMetricId } = useParams<{ metricId: string }>(); const queryClient = useQueryClient();