如何使用Apollo Client执行批量突变

sch*_*ldi 12 reactjs graphql apollo-client

我尝试将ApolloClient 2.1与新的Mutation Component一起使用。

简单的用例正在工作,但是现在我有了一些更复杂的东西。

我要实现的是查询数据并将它们放在列表中,然后对该列表进行排序(在这里通过react-sortable-hoc),一旦排序,我想为列表中的所有元素更新新位置。

因此,基础是这样的,它适用于简单的查询:

const query = gql`
{
  items( order:{by:"position", direction:"desc"}) {
    id
    name
    position
  }
}`

const ItemView extends Component {
    onSortEnd = ({ oldIndex, newIndex }) => {
       console.log("Sort ended: ", oldIndex, newIndex);
    }

    render() {
     <Query query={query}>
        {({ loading, data, error }) => {
          if (loading) return <p>Loading...</p>;
          if (error) return <p>Error</p>;

          return (
            <ItemList items={data.items} onSortEnd={this.onSortEnd} />
          )
        }}
      </Query>
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我确实在很多方面都在努力进行突变。

我想我需要包装突变成分。但是,我该如何在其中提供GraphQL查询,因为我想通过多次触发类似的查询来进行批量修改,例如

mutation {
  updateItem1: updateItem(id: 457092155, input: {position: 1}) {
    item {
      id
    }
    ok 
    errors

  },
  updateItem2: updateItem(id: 54489270, input: {position: 2}) {
    item {
      id
    }
    ok 
    errors

  },
  ... // much more mutations, one for each item in the list
}
Run Code Online (Sandbox Code Playgroud)

所以我的主要问题是,如何将具有动态数量突变的GraphQL突变传递给Mutation组件?还是应该完全不同地执行此操作?

非常感谢您的任何提示

Hem*_*har 1

为了实现这一点,您必须将多个 Mutations 组合在一起。您可以为此使用react-adopt 。他们甚至在这里解决了这个问题https://github.com/pedronauck/react-adopt#leading-with-multiple-params

您还可以查看此处进行的讨论https://github.com/apollographql/react-apollo/issues/1867 jasonpaulos有一个使用 hooks 演示这一点的示例

大家好!我相信新的 Apollo 钩子 useQuery、useMutation 和 useSubscription 足以解决这个用例。为了证明这一点,我已经转换了@Cridda使用react-adopt的示例,并将其修改为使用@apollo/react-hooks:https: //codesandbox.io/s/apollo-and-react-hooks-4vril

这个示例绝不是完美的,但它演示了钩子如何极大地简化某些用例。

希望这可以帮助!