-2
 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
4

3 回答 3

0

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.

于 2020-02-08T03:07:00.160 回答
0

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;
}
于 2020-02-10T23:06:37.763 回答
0

We can also use onCompleted method provided in useMutation if we want to process the result of the query.

于 2020-02-19T18:28:03.310 回答