TanStackT
TanStack3y ago
4 replies
dual-salmon

v3 -> v5 migration; issues with SSE

While upgrading from react-query v3 to v5, I've hit a roadblock related to custom code that subscribes to an EventSource and updates the queryData in the queryClient on each new event.

It looks like this:
const useSSECacheUpdater = <T>(
    key: CacheKey,
    subscriber: (listener: (data: T) => void) => () => void
): void => {
    const queryClient = useQueryClient();

    React.useEffect(() => {
        return subscriber((data) => {
            return queryClient.setQueryData(key, data);
        });
    }, [key, queryClient, subscriber]);
};


and gets used like this:

export const useRobotMapQuery = () => {
    useSSECacheUpdater(CacheKey.Map, subscribeToMap);
    return useQuery(CacheKey.Map, fetchMap, {
        staleTime: 1000,
    });
};


That code works fine with v3, however on v5, the SSE connection is torn down and recreated on each new event, because apparently the queryClient dependency of that useEffect changes each time, queryClient.setQueryData is called(?) I'm not 100% sure that that's actually the cause but I can say that the effect function doesn't get called on each new event anymore when I still reference the queryClient in the Effect but don't call the
setQueryData
method.


What do I need to change so that I can recreate that functionality on react-query v5?
Alternative question: What would be best practice to integrate server-sent events into React Query v5?


For reference, the code in question can be found here: https://github.com/Hypfer/Valetudo/blob/fec428f9c6c10ce59734f80cf5f6b9ee3fb4b617/frontend/src/api/hooks.ts#L245-L256
Was this page helpful?