Query doesn't work properly when initialData is used #9175
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
bobin 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
bobagain 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
TkDodo closed this
TkDodo added labelsworks as designed
@TkDodo that makes sense, thx. However when I use
placeholderDatamy ts type of the data isMyData | undefined, unlike withinitialDatawhere it correctly gets narrowed toMyData. Why is that so? Shouldn't the data always be defined withplaceholderDatatoo?Actually ignore it. I saw this now https://tkdodo.eu/blog/placeholder-and-initial-data-in-react-query#error-transitions
I can actually achieve what I want by doing:
const { data: users = [] } = useQuery({ queryKey: ['my-search', query], queryFn: async () => { console.log('**** running my-search: ', query); const response = await searchApi(query); return response; }, initialData: [], initialDataUpdatedAt: () => Date.now() - 1000 * 6, staleTime: 5 * 1000, });yes, you can. This marks initialData as “too old”, so a background refetch happens.
When I set placeholderData, and then the background fetch fail. I expect data to be undefined and error to be set
const [storedSession, setStoredSession] = useMMKVObject<ISession>(`current-user-session`); const { data, error, isError, isLoading, status, isPlaceholderData } = useQuery({ queryKey: ["session"], staleTime: 0, retry: false, placeholderData: storedSession, queryFn: async () => { const sess = await authClient.getSession(); if (sess.error) { console.log("throwing error"); // throw new Error(sess.error.message || "Something went wrong"); return Promise.reject("something went wrong"); } return { session: sess.data.session, user: sess.data.user, } satisfies ISession; }, }); console.log({ status, isPlaceholderData, data: !!data, error, storedSession: !!storedSession, isError, });As stated in
https://tkdodo.eu/blog/placeholder-and-initial-data-in-react-query#when-to-use-what. But what I saw is data is always set to the placeholderData. status is always "success", isError is false, isPlaceholderData is trueI expected after
console.log("throwing error");, data to be undefined, and error to be 'something went wrong'I am using version 5.68.0, on react native expo
Show a reproduction please
Sign in to join this conversation.
you have set
initialDataandstaleTime, so this behaviour is expected.initialDatais always taken into account when a query is created. If you change the queryKey, you create a new Query. Each query is represented as a row in the devtools, you can see it there.Once data is in the cache, react-query doesn’t know or care where it came from. Could be from initialData, could be from
queryClient.setQueryData, could be from hydration or from running the queryFn.Data respects staleTime, so as long as data is fresh, the queryFn won’t run. So if you set
initialData: [], you put that into the cache every time you change the queryKey, and then you say “this is good data for 5 seconds”, so the queryFn doesn’t need to run.You might be looking for
placeholderData, you can read about the differences here: