Skip to content

streamedQuery reducer being called twice #9787

@iSplasher

Description

@iSplasher

Describe the bug

It seems the streamedQuery's reducer is being called twice, resulting in duplicated values.
Please see the relevant code:

https://github.com/TanStack/query/blob/ecdf96296b1dfcee617a5a5b9afdf2a42ad436ba/packages/query-core/src/streamedQuery.ts#L83C1-L89C38

      // don't append to the cache directly when replace-refetching
      if (!isRefetch || refetchMode !== 'replace') {
        context.client.setQueryData<TData>(context.queryKey, (prev) =>
          reducer(prev === undefined ? initialValue : prev, chunk),
        )
      }
      result = reducer(result, chunk)

As you can see, reducer gets called once in the setQueryData under special conditions, and then again at the end of the loop. This can mess up a stateful object in a custom reducer.

Your minimal, reproducible example

It's very simple

Steps to reproduce

const arr = [];

queryOptions({
    queryKey: ["somekey"],
    queryFn: streamedQuery({
      streamFn: async function* (ctx) {
        const v = [1, 2, 3];
        yield* v;
      },
      reducer: (oldStream, newChunk) => {
        arr.push(newChunk);
        return [...oldStream, newChunk];
      },
      initialValue: [],
      refetchMode: "replace",
    }),

arr.length == 6

Expected behavior

Reducer gets called once per chunk.

How often does this bug happen?

None

Screenshots or Videos

No response

Platform

Windows

Tanstack Query adapter

None

TanStack Query version

v5.90.5

TypeScript version

No response

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions