【问题标题】:Graphql mutation query : how to access the data elementsGraphql 变异查询:如何访问数据元素
【发布时间】:2020-05-24 01:22:03
【问题描述】:
 const MUTATION_QUERY = gql`
  mutation MUTATION_QUERY(
    $name: bigint!
  ) {
    insert_name(
      objects: {
        name: $name
      }
    ) {
      returning {
        id
        name
      }
    }
  }
`;


const [onClick, { error, data }] = useMutation<{}, {}>(MUTATION_QUERY, {
        variables: {
          name: 1234,
        },
      });

我的变异查询在我的表中插入名称并自动生成 id。在控制台记录数据变量时,我可以查看数据对象中的字段 id 和 name。但我无法单独访问它们。我怎样才能 console.log “id”。谢谢你。

console.log(data) 看起来像:{insert_name: {...}}

扩展为:

insert_name: 
 returning: Array(1) 
   0: {id: 1, name: 1234} 
   length: 1 
   _proto_: Array(0) 
 _typename: "insert_name_mutation_response

【问题讨论】:

  • 问题的标题和标签具有误导性 - 这是一个关于访问对象中嵌套属性的基本 JavaScript 问题。有一个很好的答案here

标签: reactjs typescript graphql frontend graphql-mutation


【解决方案1】:

如果我们想处理查询的结果,我们也可以使用 useMutation 中提供的 onCompleted 方法。

【讨论】:

    【解决方案2】:

    console.log(data.insert_name.returning[0].id) 会给你返回的 id。

    为了让它在打字稿中工作,我们需要更改查询以添加数据的返回类型

    const [onClick, { error, data }] = useMutation<{ReturnInsertNameProps}, {}>(MUTATION_QUERY, {
            variables: {
              name: 1234,
            },
          });
    
    interface ReturnInsertNameProps {
      insert_name: ReturnQueryProps;
    }
    
    interface ReturnProps {
      returning: MessageProps[];
    }
    
    interface NameProps {
      id: number;
      name: number;
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用.访问对象的字段

      例如,如果您的对象看起来像这样 -

      data = {
        id: 1,
        name: 'Jane',
      }
      

      您可以通过data.id 获取ID

      无论你的对象有多深,这都有效,所以举这个例子 -

      data = {
        person: {
          id: 1,
          name: 'Jane',
        }
      }
      

      您可以使用data.person.id 获取人的ID。

      【讨论】:

      • 这不起作用。我已经用 console.log(data) 的输出更新了我的问题。谢谢。
      猜你喜欢
      • 1970-01-01
      • 2019-08-28
      • 1970-01-01
      • 2011-07-27
      • 2020-01-21
      • 2019-06-22
      • 1970-01-01
      • 2021-04-24
      • 2022-12-19
      相关资源
      最近更新 更多