-
I created a custom hook that has both export const useFruits = (query: string) => {
return useQuery<SuccessResponse>({
queryKey: ["fruits", query],
queryFn: async () => {
await new Promise((resolve) => setTimeout(resolve, 2000)); // emulate network latency
return {
fruits: fruits.filter((fruit) =>
fruit.toLowerCase().startsWith(query.toLowerCase())
),
query,
};
},
initialData: {
fruits: ["Banana", "Blackberry"],
query,
},
placeholderData: keepPreviousData,
});
}; I added const Fruits = () => {
const [query, setQuery] = useState("b");
const fruitsInfo = useFruits(query); // fruitsInfo.data will never be undefined
const { fruits, query: highlightQuery } = fruitsInfo.data;
console.log({
isFetching: fruitsInfo.isFetching,
fruits,
highlightQuery
});
// Render matched fruits here and highlight the text matching `highlightQuery`
}; I also added However, when I change the query from "b" to "bb", I see:
Why is Is it ok to use This article by @TkDodo implies that we should use one or the other 🤔 Here is a CodeSandbox that demonstrates the actual "real-life" issue. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
it doesn’t achieve much. |
Beta Was this translation helpful? Give feedback.
what do you mean with too early? From what I can see, everything is fine in the sandbox.
I type in “a”. This creates a new query with “fruits, a”, and I get back:
those values come from the
initialData
passed, which is fine.Then I type “b”. The query is now “ab”, so it creates a new query “fruits, ab”. That again gets
initialData
(because that’s what the code does - it’s a completely new query), so we get:if you’d expected
h…