Less hacky way to do a simple filter (sandbox code included)
I want it to fetch on the first loading, and if the user wants to search something, filter from the loaded data. This is the way I made it work, but I feel i'm not using fully react query.
https://codesandbox.io/s/trusting-hill-fvq8qe?file=/src/App.js
gmcamposano
CodeSandbox
trusting-hill-fvq8qe - CodeSandbox
trusting-hill-fvq8qe by gmcamposano using @tanstack/react-query, react, react-dom, react-scripts
3 Replies
vicious-gold•3y ago
I think this is a pretty good start! The main feedback that I would have would be that instead of having a state containing the
filteredProducts, you could simply store the search term in state.
Then during render you can have something like:
That'll simplify the JSX (then you just have to render productsToDisplay) and you just keep one source of truth. The potential issue with a filteredProducts state is that it could become stale. Say a product is removed in the backend and the list is refetched by the query, and that removed product happened to have been in the list of filteredProducts , it'll still get displayed.generous-apricotOP•3y ago
Hello! Thank you for your response
I will try it out right now
Isn't searchTerm a state variable?
@julien You are correct. It worked great and simplified everything
vicious-gold•3y ago
Glad to hear!!