T
TanStack11mo ago
deep-jade

in search data is falling back to placeholder, due to key change

I am implementing a search on click, but when I change the searchBy the data falls back to the placeholder data, which is expected. since it's a different key that points to a different cache. tha solution, I found is to remove the searchBy from key, but eslint is not happy, is there any other recommended way to do this?
const [searchBy, setSearchBy]
= useState()

const { data, refetch } = useQuery({
enabled: false,
queryKey: ["todo", searchBy],
queryFn: () => searchTodo(searchBy),
placeholderData: []
});

return <>
<input onChange={(e) => setSearchBy(e.target.value)}>
<button onClick={() => refetch}> search<button>

{data.map((todo)=> <div key={todo.id}>{todo.name}/div>
</>
const [searchBy, setSearchBy]
= useState()

const { data, refetch } = useQuery({
enabled: false,
queryKey: ["todo", searchBy],
queryFn: () => searchTodo(searchBy),
placeholderData: []
});

return <>
<input onChange={(e) => setSearchBy(e.target.value)}>
<button onClick={() => refetch}> search<button>

{data.map((todo)=> <div key={todo.id}>{todo.name}/div>
</>
5 Replies
unwilling-turquoise
unwilling-turquoise11mo ago
Definitely do not remove searchBy from the queryKey. It's a dependency array essentially like with useEffect You probably want keepPreviousData hold on this has been removed ignore this message and I'm very sorry for that.
unwilling-turquoise
unwilling-turquoise11mo ago
Migrating to TanStack Query v5 | TanStack Query React Docs
Breaking Changes v5 is a major version, so there are some breaking changes to be aware of: Supports a single signature, one object useQuery and friends used to have many overloads in TypeScript differ...
unwilling-turquoise
unwilling-turquoise11mo ago
Sorry: what you want to do is pass a function to placeholderData and that will take the previous data as an argument. (And keepPreviousData is in fact the name of a function you can use for this)
ratty-blush
ratty-blush11mo ago
Yep, this is it ⬆️
deep-jade
deep-jadeOP11mo ago
okay, I will try it, thanks

Did you find this page helpful?