v5 placeholderData doesn't work with select option
Hello!
I have this case where my queries are using select to transform the data on the observer level. In v4 I can use
keepPreviousData: true to preserve the previous data while new data is being fetched. Example here -> https://codesandbox.io/s/goofy-brook-q0lvjj?file=/src/App.js
Now in v5, we're retiring keepPreviousData and using placeholderData to also keep previous data. But this doesn't quite the same way as v4
Example here -> https://codesandbox.io/s/gallant-gates-dslrlm?file=/src/App.js
The v5 example wont keep previous data the same way as v4. Any idea how I can achieve the same functionality in v5? Also in v5, if you remove the select function then it works as expected. So not sure if this is intentional5 Replies
wee-sapphire•3y ago
oh that's a sneaky bug. The problem seems to be that we pass the
selected result into the placeholder data function as previousData. So you're getting the name there, returning it. Then, we pass that to select. Now, you get a string there as well and try to select .name from it, which is undefined. So we transform back to undefined, which is a hard loading state
so the problem is that we need to pass the un-selected data into the placeholderData function
I think it's as straight-forward as to replace
https://github.com/TanStack/query/blob/01ee84997b3cf9fe39861bb31452c8f2ede8f00c/packages/query-core/src/queryObserver.ts#L493 prevQueryResult?.data (which is the already selected result) with prevResultState?.data`, which should be the raw prev data 🤔
the result of this will run through select again anyways...
we should add a bunch of tests for this 😅
can you file an issue? of course you can also work on it if you wantabsent-sapphireOP•3y ago
Awesome thanks!!! I'll make a PR to fix this today. Seems like this functionality works in a similar fashion in v4 too? Should I make a PR to the main branch? Or would this be considered a breaking change a PR to alpha would be more appropriate?
wee-sapphire•3y ago
It works in v4 because we basically early return when we have
keepPreviousData. We store the previous selected result and just return that.
In v5, this branch doesn't exist anymore, so we have to go through placeholderData, which happens later. There, I just passed the wrong thing to the function 😅 . The type assertion shows this - it's actually unnecessary once we pass the right thing. And then, what is returned from there also runs trough select, so we'll get the correct data eventually.
Even better, it seems that previousQueryResult is then entirely unused, so a bit more code to delete 🙌
so yeah it's only relevant for alpha pleaseabsent-sapphireOP•3y ago
Okay makes sense! Thanks for the clarification 🥳
wee-sapphire•3y ago
thanks for fixing this ❤️