How to handle search with tanstack query?
If you have a form with lets say
search, sort, category etc. What is the best way to trigger a search, which returns results? The search should be triggered by form submission.
Is this the way to go?
Seems kind of odd to me.7 Replies
foreign-sapphire•2mo ago
Why is that odd?
foreign-sapphire•2mo ago
It's the same as we have in the docs here: https://tanstack.com/query/v5/docs/framework/react/guides/disabling-queries#lazy-queries
Disabling/Pausing Queries | TanStack Query React Docs
If you ever want to disable a query from automatically running, you can use the enabled = false option. The enabled option also accepts a callback that returns a boolean. When enabled is false: If the...
foreign-sapphire•2mo ago
It just looks better because the components are split apart
conscious-sapphireOP•2mo ago
It seems odd because you have the same state twice. In the world "before tanstack query", you would just have stale version of the current form data on submit, execute some async function, and set some search result state.
But in this case we just change the params for the query, which are also duplicated in the form state itself. This enforces you to sync the params for the query always with the form data. E.g. if you reset the form, you also have to reset
submittedParams.
Splitting it into components, makes it more clear, yes. Most of the library felt "just right" this was one thing that striked me as odd. It's a different mental model, I might just have to get used to it. I probably have to think more in terms of Server State (submittedParams) vs Client State (form data).foreign-sapphire•2mo ago
It's not the same state though. One is current filters and one is applied filters.
If i click submit and then change filters, they are different
Try disabling the submit button when the current filters are the same as the applied ones. Doesn't work with just one state
conscious-sapphireOP•2mo ago
Yes, but previously this state of the current filters did not have to be persisted, but since they are part of the keys it makes sense to persist the current state of filter. Normally you would only have the results as a state.
Yeah thats a good use case
Might be a best practise to just store it in a state, even in traditional fetching
foreign-sapphire•2mo ago
Wdym normally? Your form doesn't necessarily need state, it could be uncontrolled too and you grab the state in the onSubmit handler and store it somewhere
Put applied state in the url, that way it becomes sharable. And keep the "current" state as an implementation detail of the form component