TanStackT
TanStack4mo ago
12 replies
comprehensive-tomato

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?
const [form, setForm] = useState({
  search: "",
  sort: "relevance",
  category: "all",
});

// state that actually triggers the query
const [submittedParams, setSubmittedParams] = useState(null);

const { data, isFetching, isError } = useQuery({
  queryKey: ["products", submittedParams],
  queryFn: async () => {
    return searchPosts(submittedParams)
  },
  enabled: !!submittedParams, // only run after first submit
});

const handleSubmit = () => {
  setSubmittedParams(form);
};


Seems kind of odd to me.
Was this page helpful?