There is a search result page where query params are passed to useQuery. On this page, we can change our search prompt (query param essentially) however I only want to refetch when user click "Search" button.
I’ve tried setting enabled:false
and refetch()
on button click, however in this case I don’t get data when page mounts. Is there any way to fetch data only once on mount and then manually refetch with new params?
I had an idea of using refetch()
in useEffect but it doesn’t look like the right way to do it
Example code:
-model.ts
const useSearch = (params) => {
<some logic with params>
return useQuery<Type>(['/search' + params], {enabled: false})
-view.tsx
const {query, push} = useRouter()
const {data, refetch} = useSearch(query.search)
const handleSearchParams = (v) => {push({query: {search: v})}
return(
<...>
<Input onChange={handleSearchParams} value={query.search} />
<Button onClick={refetch}>Search</Button>
<...>
)
2
Answers
Setting enabled: false in the useQuery options, the initial data fetching is disabled. This allows you to manually trigger the fetch when needed.
Add a useEffect hook to refetch the data when the search param changes
the data will be fetched once on mount and then refetched whenever the search param changes due to the useEffect hook.
You’re approaching the solution from the wrong direction. You don’t need to "gate" or otherwise control when react-query ‘re-fetches’. What you should be doing instead is gating when your query key is being changed.
e.g.