Description
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.
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
- Go to https://stackblitz.com/edit/tanstack-query-uatj7auc?file=src%2Findex.tsx
- Type
bob
in the input and observe nothing happening - 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
- 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,
});
- 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
- OS: macOS
- browser: Brave
- version: Version 1.76.74 Chromium: 134.0.6998.89 (Official Build) (arm64)
Tanstack Query adapter
react-query
TanStack Query version
5.76.1
TypeScript version
5.76.1