You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I added initialData because I fetch the data in a Server Component in Next.js app and it's available to populate the cache on the client. Also, I like how TypeScript understands that data will always exist:
constFruits=()=>{const[query,setQuery]=useState("b");constfruitsInfo=useFruits(query);// fruitsInfo.data will never be undefinedconst{ 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 placeholderData: keepPreviousData because I'd like to show the user the previous data while the new data is being fetched.
However, when I change the query from "b" to "bb", I see:
{
"isFetching": true,
"fruits": [
"Banana",
"Blackberry"
],
"highlightQuery": "bb" // why not still "b" here?
}
{
"isFetching": false,
"fruits": [],
"highlightQuery": "bb" // only here I expect it to be "bb"
}
Why ishighlightQuery updated before we get the result?
Is it ok to use initialData with previousData in the same useQuery?
Here is a CodeSandbox that demonstrates the actual "real-life" issue.
Initially, "b" is highlighted. When I update the query to "bb" you can see that the highlight disappears (because highlightQuery is updated before we get the result).
What's the best way to fix this?
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
I created a custom hook that has both
initialData
andplaceholderData
:I added
initialData
because I fetch the data in a Server Component in Next.js app and it's available to populate the cache on the client. Also, I like how TypeScript understands that data will always exist:I also added
placeholderData: keepPreviousData
because I'd like to show the user the previous data while the new data is being fetched.However, when I change the query from "b" to "bb", I see:
Why is
highlightQuery
updated before we get the result?Is it ok to use
initialData
withpreviousData
in the sameuseQuery
?This article by @TkDodo implies that we should use one or the other 🤔
Here is a CodeSandbox that demonstrates the actual "real-life" issue.
Initially, "b" is highlighted. When I update the query to "bb" you can see that the highlight disappears (because
highlightQuery
is updated before we get the result).What's the best way to fix this?
Beta Was this translation helpful? Give feedback.
All reactions