T
TanStack•3y ago
wise-white

How to use react-query for a request with filters

I have created a small example in codeSandBox. (https://codesandbox.io/s/loving-tamas-lxprg4?file=/src/App.js) I want to use react-query in order to fetch data based on filters. In the example, there are two components the <Filters/> where the filters and the search button, and the <DisplayData/> where the fetched data is going to be displayed. The inputs in <Filters/> are controlled and my problem is that I can't find a solution without using two different states for the same values (filters). I have added as query keys the filters in order to re-trigger the query each time the filters change, so I need one state to keep the filters for query keys. I set this state at the click of the search button. The other state is for the values for controlled inputs. And set the state on each change of the inputs. Is there someone who has a better solution?
christosno
CodeSandbox
loving-tamas-lxprg4 - CodeSandbox
loving-tamas-lxprg4 by christosno using @tanstack/react-query, loader-utils, react, react-dom, react-scripts
3 Replies
modern-teal
modern-teal•3y ago
- move temporary / unapplied filter state into the Filters component, or use uncontrolled inputs - store state of applied filters in the parent component
wise-white
wise-whiteOP•3y ago
Thank you @TkDodo 🔮 , I really admire your work. You are right the temporary state should move to Filters Component, It was my fault while I was creating the example. I need to use controlled inputs as I am using an internal company library. Is there any way to avoid using two different states with more or less the same information?
modern-teal
modern-teal•3y ago
it's not the same information. I can set firstName: foo; lastName: foo and hit apply, then change it to firstName: bar; lastName: bar without submitting, in which case you want to show the queried data for foo while the filters show bar. if you don't want to use uncontrolled forms, you need two states. Note that for filters, it's often a good idea to store the applied values in the url as query params

Did you find this page helpful?