Skip to content

Query doesn't work properly when initialData is used #9175

Closed as not planned
Closed as not planned
@jbojcic1

Description

@jbojcic1

Describe the bug

I have a component that looks like this:

const data = [
  {
    id: 1,
    name: 'bob_bobovski',
  },
  {
    id: 2,
    name: 'branko',
  },
  {
    id: 3,
    name: 'bobonja',
  },
  {
    id: 4,
    name: 'boby',
  },
  {
    id: 5,
    name: 'boro',
  },
  {
    id: 6,
    name: 'jozo_kapula',
  },
];

const searchApi = async (query: string) => {
  if (!query) {
    return [];
  }
  const results = data.filter((x) => x.name.startsWith(query));
  await new Promise((resolve) => setTimeout(resolve, 1000));
  return results;
};

function Example() {
  const [query, setQuery] = useState<string>('');

  const { data: users } = useQuery({
    queryKey: ['my-search', query],
    queryFn: async () => {
      console.log('**** running my-search: ', query);
      const response = await searchApi(query);
      return response;
    },
    initialData: [],
    staleTime: 5 * 1000,
  });

  return (
    <div>
      <div>My page</div>
      <br />
      <br />
      <label>
        Search:
        <br />
        <input
          type="text"
          name="query"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
        />
      </label>
      <br />
      <br />
      <div>Users:</div>
      <br />
      <ul>
        {users.map((user) => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}

when I type in the input I expect the query to run and component to display filtered users. However nothing happens when I start typing. I don't see **** running my-search log in the console and in the tanstack dev tools I see disabled queries (see screenshot below). E.g. I type bobo and nothing happens. It only starts working if I wait for a bit and then delete some chars.

Image

Now if I remove initialData it starts behaving as expected.

You can try it yourself in the stackblitz example I provided below.

Your minimal, reproducible example

https://stackblitz.com/edit/tanstack-query-uatj7auc?file=src%2Findex.tsx

Steps to reproduce

  1. Go to https://stackblitz.com/edit/tanstack-query-uatj7auc?file=src%2Findex.tsx
  2. Type bob in the input and observe nothing happening
  3. Wait for a few seconds and then delete last later. Observe how results are now showing up and if you type again it works normally now
  4. Update the useQuery in the code to remove initial data. So make it:
const { data: users = [] } = useQuery({
  queryKey: ['my-search', query],
  queryFn: async () => {
    console.log('**** running my-search: ', query);
    const response = await searchApi(query);
    return response;
  },
  staleTime: 5 * 1000,
});
  1. Reload the app and type bob again and observe how it now works normally

Expected behavior

Shouldn't initialData only be returned for initial render when the query is empty string and when I start typing it should actually execute the queryFn and return results or am I missing something?

So basically I am expecting the same behavior that I am seeing without initialData after initial render.

How often does this bug happen?

Every time

Platform

Tanstack Query adapter

react-query

TanStack Query version

5.76.1

TypeScript version

5.76.1

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions