TanStackT
TanStack3y ago
12 replies
slow-yellow

useQuery for search

Hi everyone! Was wondering if anyone could help me figure out the best way to implement a search page such as this with React Query.

I would like a controlled search bar that the top which the user can type into. Although I do not want it to search until they have clicked the search button, I do want to be showing results initial so I would like it to fire a query when the page mounts with the default value.

Below is the code I have managed to come up with. I am using derived state so that I can control the input and but not update the query key (this firing a new query) until the user clicks the search button. Is there a better solution than this which removes this bad practice?

Thanks all!
import { useState } from 'react' import { useQuery } from '@tanstack/react-query' import axios from 'axios' function App() { const [searchTerm, setSearchTerm] = useState("1") const [queryParams, setQueryParams] = useState(searchTerm) const { data } = usePerson(queryParams) const handleSearch = () => setQueryParams(searchTerm) return ( <div> <input onChange={(e) => setSearchTerm(e.target.value)} /> <button onClick={handleSearch}>Search</button> <div>{data?.name}</div> </div> ) } const usePerson = (queryParams: string) => { return useQuery({ queryKey: ["person", queryParams], queryFn: () => fetchPerson(queryParams) }) } const fetchPerson = async (queryParams: string) => { const { data } = await axios.get(https://swapi.dev/api/people/${queryParams}`)
return data
}

export default App
`
Was this page helpful?