【问题标题】:Return value from mutation is empty and/or undefined突变的返回值为空和/或未定义
【发布时间】:2019-06-04 09:35:22
【问题描述】:

当使用 apollo-link-state 运行 @client 突变时,解析器的响应仅仅是:

{ data: {}, errors: undefined }

从我返回的解析器 {data: { ...product }}。 如果产品是具有多个值的对象,其中一个 __typename.

我尝试将返回值设置为各种值,例如 return product, return { data: product }, return { data: { data: { product }}}等。等等。我想你明白了。

解析器:

export const updateInventoryItem = async (product, cache) => {
  const query = gql
    query {
      inventory @client {
        ...omitted, but all the values
    }
   };

   const prevState = await cache.readQuery({ query });
   const prevInventory = prevState.inventory;

   const productIndex = prevInventory.findIndex(x => x.id === 
   product.id);
   prevInventory.splice(productIndex, 1);

   const data = {
    inventory: [
     product,
     ...prevInventory
    ]
   }

  await cache.writeQuery({ query, data });

  return {data: { ...product }}
 }

变异:

const UPDATE_ITEM = gql
  mutation updateInventoryItem($product: InventoryItem!) {
    updateInventoryItem(product: $product) @client {
      __typename
      id
      ...and so on
    }
  }
;

调用突变的函数:

updateItem = () => {
    this.props.updateItem({
      variables: {
        product: {
          __typename: this.state.item.__typename,
          id: this.state.item.id,
          addedToCart: this.state.item.addedToCart,
          ...and so on
        }
      }
    }).then((e) => {
      console.log(e);
      this.setState({ savedRecently: true })
    },
      err => console.log(err))
  }

首先:很抱歉要翻阅这么长的代码块。

上述代码的预期结果是解析器返回刚刚添加的产品,例如 { data: {...product}, errors: undefined },但它返回 { data: {}, errors: undefined } 如开头所述。

如果您需要更多信息,或者我遗漏了什么,请告诉我。

【问题讨论】:

    标签: react-apollo apollo-client apollo-link-state


    【解决方案1】:
    const UPDATE_ITEM = gql
      mutation updateInventoryItem($product: InventoryItem!) {
        return updateInventoryItem(product: $product) @client {
          __typename
          id
          ...and so on
        }
      }
    ;
    

    这个函数当然需要返回一个值,但这还不是全部。

    GraphQL(在本例中为 Apollo-Client),期望像响应一样形成一个对象,你告诉它你想要的。

    在这种情况下:

    updateInventoryItem(product: $product) @client {
          __typename
          id
          ...and so on
        }
    

    这要求获取一个带有 __typename 和 id 以及您放入其中的任何其他内容的对象。

    总而言之,我犯了一个愚蠢的错误,但由于没有答案,如果有人和我一样掉入同一个坑,这里有一些东西可以尝试。

    【讨论】:

      猜你喜欢
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-17
      • 1970-01-01
      • 1970-01-01
      • 2019-05-17
      • 2020-01-02
      相关资源
      最近更新 更多