How to execute useLazyQuery programmatically?

Viewed 6029

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.

2 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

I'm gonna go ahead and steal @Daniel's answer :)

The following code accomplishes the goal

const

skip = R.complement (H.isNotNilOrEmpty) (str),

{data} = useQuery (QUERY_SEARCH, {variables: {str}, skip}),

sorry for using undefined variables R and H but hopefully the method names are descriptive

Related