-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
Tanu
  • 1,286
  • 4
  • 16
  • 35
  • The question's title and tags are misleading - this is a basic JavaScript question about accessing nested properties in objects. There is an excellent answer [here](https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json). – Robin Métral Feb 19 '20 at 18:33

3 Answers3

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.

Kyle Soeltz
  • 306
  • 1
  • 9
  • This does not work. I have updated my question with the output of console.log(data). Thank you. – Tanu Feb 10 '20 at 15:19
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;
}
Tanu
  • 1,286
  • 4
  • 16
  • 35
0

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

Tanu
  • 1,286
  • 4
  • 16
  • 35