Wait for useLazyQuery response

Viewed 13982

I need to call a query when submit button is pressed and then handle the response.

I need something like this:

const [checkEmail] = useLazyQuery(CHECK_EMAIL)
const handleSubmit = async () => {
  const res = await checkEmail({ variables: { email: values.email }})
  console.log(res) // handle response
}

Try #1:

const [checkEmail, { data }] = useLazyQuery(CHECK_EMAIL)
const handleSubmit = async () => {
  const res = await checkEmail({ variables: { email: values.email }})
  console.log(data) // undefined the first time
}

Thanks in advance!

3 Answers

This works for me:

const { refetch } = useQuery(CHECK_EMAIL, {
  skip: !values.email
})

const handleSubmit = async () => {
  const res = await refetch({ variables: { email: values.email }})
  console.log(res)
}

After all, this is my solution.

export function useLazyQuery<TData = any, TVariables = OperationVariables>(query: DocumentNode) {
  const client = useApolloClient()
  return React.useCallback(
    (variables: TVariables) =>
      client.query<TData, TVariables>({
        query: query,
        variables: variables,
      }),
    [client]
  )
}

You could also use the onCompleted option of the useLazyQuery hook like this:

const [checkEmail] = useLazyQuery(CHECK_EMAIL, {
  onCompleted: (data) => {
    console.log(data);
  }
});

const handleSubmit = () => {
  checkEmail({ variables: { email: values.email }});
}
Related