query emit on

This commit is contained in:
Nate Kelley 2025-02-15 20:45:11 -07:00
parent 5b4da9fc4a
commit 2f0bc40cfd
No known key found for this signature in database
GPG Key ID: FD90372AB8D98B4F
2 changed files with 19 additions and 6 deletions

View File

@ -1,5 +1,10 @@
import type { BusterSocketResponseRoute, BusterSocketRequest } from '@/api/buster_socket'; 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 type { InferBusterSocketResponseData } from './types';
import { useBusterWebSocket } from '@/context/BusterWebSocket'; import { useBusterWebSocket } from '@/context/BusterWebSocket';
import { useEffect } from 'react'; import { useEffect } from 'react';
@ -20,20 +25,29 @@ export const useSocketQueryEmitOn = <
| null, | null,
enabledTriggerProp?: boolean | string enabledTriggerProp?: boolean | string
) => { ) => {
const queryClient = useQueryClient();
const busterSocket = useBusterWebSocket(); const busterSocket = useBusterWebSocket();
const enabledTrigger = enabledTriggerProp ?? true; const enabledTrigger = enabledTriggerProp ?? true;
const emitQueryFn = useMemoizedFn(async () => { const emitQueryFn = useMemoizedFn(async () => {
const queryState = queryClient.getQueryState(options.queryKey);
if (!queryState) {
busterSocket.emit(socketRequest); busterSocket.emit(socketRequest);
}
}); });
const queryResult = useSocketQueryOn(socketResponse, options, callback);
useEffect(() => { 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(); emitQueryFn();
} }
}, [enabledTrigger]); }, [enabledTrigger]);
const queryResult = useSocketQueryOn(socketResponse, options, callback);
return { ...queryResult, refetch: emitQueryFn }; return { ...queryResult, refetch: emitQueryFn };
}; };

View File

@ -17,7 +17,6 @@ import { useQueryClient } from '@tanstack/react-query';
import { queryKeys } from '@/api/query_keys'; import { queryKeys } from '@/api/query_keys';
export const useBusterMetricsIndividual = () => { export const useBusterMetricsIndividual = () => {
const [isPending, startTransition] = useTransition();
const { metricId: selectedMetricId } = useParams<{ metricId: string }>(); const { metricId: selectedMetricId } = useParams<{ metricId: string }>();
const queryClient = useQueryClient(); const queryClient = useQueryClient();