如何将 apollo 客户端中的突变链接在一起

How to chain together Mutations in apollo client

我有一堆信息存储在我的状态中,我需要使用突变传递给我的 graphQL 服务器,但我需要在调用下一个突变之前使用每个突变的结果,因为我需要:

我注意到 apollo Mutation 组件有一个 onCompleted 回调,但我不知道如何使用这个回调来触发另一个 mutation 或者它是否是解决我的问题的正确方法。我还研究了批处理我的突变以一次发送它们,但它似乎也不是解决方案。任何帮助将不胜感激

正如您所提到的,解决它的独特方法是对所有突变进行批处理,查看 issue related!

其实编起来也不错,你可以这样做:

const handleClick = async (mutation1Fn, mutation2Fn, mutation3Fn) => {
  const data1 = await mutation1Fn()
  const data2 = await mutation2Fn()
  const data3 = await mutation3Fn()
}

const Mutations = () => (
  <Composer
    components={[
      <Mutation mutation={mutation1} />,
      <Mutation mutation={mutation2} />,
      <Mutation mutation={mutation3} />
    ]}
  >
    {([mutation1Fn, mutation2Fn, mutation3Fn]) => (
      <button
        onClick={() => handleClick(mutation1Fn, mutation2Fn, mutation3Fn)}
      >
        exec!
      </button>
    )}
  </Composer>
)

如果您遇到困难,请告诉我!

您需要做的就是根据传递的数据嵌套这些突变。

onCompletedonError 道具可以用在你的案例中,它们也可以访问新的数据结果。但我个人认为嵌套格式更易读,也更容易后期调试。

它会是这样的:

const Mutations = () => (
  <Mutation mutation={m1}>
    {(mutation1, { loading, error, data }) => (
       if (loading) return `Loading...`
       if (error) return `Error...`

       const id = get(data, 'result.id')

       return (
          <Mutation mutation={m2} variables={id} />
            {(mutation2, { loading, error, data }) => (

             if (loading) return `Loading...`
             if (error) return `Error...`

             (...)
            )}
          </Mutation>
     )}
  </Mutation>
)