简体   繁体   中英

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. On console logging the data variable I can view the fields id and name in the data object. But I am not able to access them them individually. How can I console.log "id". Thank you.

the console.log(data) looks like : {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

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 .

console.log(data.insert_name.returning[0].id) will give you the id returned.

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 方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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