简体   繁体   English

Graphql 突变查询:如何访问数据元素

[英]Graphql mutation query : how to access the data elements

 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,
        },
      });

My mutation query is inserting name in my table and autogenerating the id.我的变异查询正在我的表中插入名称并自动生成 id。 On console logging the data variable I can view the fields id and name in the data object.在控制台记录数据变量时,我可以查看数据对象中的字段 id 和 name。 But I am not able to access them them individually.但我无法单独访问它们。 How can I console.log "id".我怎样才能 console.log “id”。 Thank you.谢谢你。

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

which expands to :扩展为:

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

You can access the fields of an object with .您可以使用 访问对象的字段.

For example, if your object looks like this -例如,如果您的对象看起来像这样 -

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

You can get just the id with data.id您可以使用data.id仅获取 id

This works no matter how many layers deep your object may go, so take this example -无论您的对象有多少层深度,这都有效,因此以这个例子为例 -

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

You could get the id of person with data.person.id .您可以通过data.person.id获取人员的 id。

console.log(data.insert_name.returning[0].id) will give you the id returned. console.log(data.insert_name.returning[0].id)会给你返回的id。

For it to work in typescript we need to change the query to add the return type of data为了让它在打字稿中工作,我们需要更改查询以添加数据的返回类型

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;
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM