Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute useLazyQuery programmatically?

Ok, I understand React Apollo's useLazyQuery executes only once its first argument is called. But I was disappointed to learn that after that it behaves like useQuery.

So: How to control when useLazyQuery fires? My use case is pretty simple: I have an 'autocomplete' search bar. I don't want to query when the input is empty. I can easily do that on first 'emptiness', but I can't find a way to disable the query when the user deletes the whole input.

like image 923
Dominik Teiml Avatar asked Aug 09 '26 22:08

Dominik Teiml


1 Answers

Ok found the answer even before I posted :)

Looks like if your query has variables, Apollo Client won't run it until you supply them. So for my use case:

const [execQuery, {data}] = useLazyQuery (QUERY_SEARCH)
useEffect (() => {
  str && (() => {
    execQuery ({variables: {str}})
  })()
}, [str])

const results = R.isEmpty (str) ? null : data
like image 121
Dominik Teiml Avatar answered Aug 11 '26 12:08

Dominik Teiml



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!