skip to Main Content

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


  1. 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

    useEffect(() => {
      refetch();
    }, [query.search])
    

    the data will be fetched once on mount and then refetched whenever the search param changes due to the useEffect hook.

    Login or Signup to reply.
  2. 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.

    const {query, push} = useRouter()
    const [activeQuery, setActiveQuery] = useState(query.search);
    const {data} = useSearch(activeQuery)
    const handleSearchParams = (v) => {push({query: {search: v})}
    const handleOnClick = () => { setActiveQuery(query.search) }
    
    return(
    <...>
        <Input onChange={handleSearchParams} value={query.search} />
        <Button onClick={handleOnClick}>Search</Button>
    <...>
    )
      
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search