【问题标题】:Wait for useLazyQuery response等待 useLazyQuery 响应
【发布时间】:2020-09-19 04:21:15
【问题描述】:

我需要在按下提交按钮时调用查询,然后处理响应。

我需要这样的东西:

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

尝试#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
}

提前致谢!

【问题讨论】:

    标签: reactjs graphql apollo-client


    【解决方案1】:

    这对我有用:

    const { refetch } = useQuery(CHECK_EMAIL, {
      skip: !values.email
    })
    
    const handleSubmit = async () => {
      const res = await refetch({ variables: { email: values.email }})
      console.log(res)
    }
    

    【讨论】:

    • 在@apollo/react-hooks@4.0.0 中,重新获取接受参数作为变量(无需放入变量属性。所以它是refetch({ email: values.email })
    【解决方案2】:

    毕竟,这是我的解决方案。

    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]
      )
    }
    

    【讨论】:

    • 谢谢你,伙计!这很棒。
    • 这只是客户端/阿波罗客户端的闭包,因此响应被保存在闭包中 - 它不会立即被调用吗? UseLazy 应该随时待命——但我想这对客户来说并不重要,所以我想这真的很好!脑洞大的东西!困惑和感兴趣,希望得到更多细节。
    猜你喜欢
    • 2021-09-26
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 2018-11-02
    相关资源
    最近更新 更多