0

I have successfully created a graphql mutation that allows me to create a Staff record.

mutation addNewStaff {
  createStaff(input: {
    first_name: "Test Name"
    last_name: "Lname"
    nickname: "Nname"
    positionId: 10
    divisionId: 6
    contact_numbers: [
      {number: "66643535"}
      {number: "876876867"}
    ]
    emails: [
      {address: "testuser@gmail.com"}
      {address: "gfdsaasd@gmail.com"}
    ]
    office_location: "OP" 
  }) {
    id
    first_name
    last_name
  }
}

the result is

{
  "data": {
    "createStaff": {
      "id": "16",
      "first_name": "Test Name",
      "last_name": "Lname"
    }
  }
}

the emails and contact_numbers are dynamic fields meaning a Staff can have unlimited number of emails and contact numbers(these are stored in a separate database tables with foreign key to the staff table). I am now writing the frontend code for this project using react and apollo client. I am very confused on how to write the gql code for creating a mutation. I cant find a good example on what I am trying to accomplish. Can someone guide me on how to accomplish this?

Marco Daniel
  • 5,467
  • 5
  • 28
  • 36
thevinci
  • 11
  • 5
  • Possible duplicate of [Graphql with nested mutations?](http://stackoverflow.com/questions/42670733/graphql-with-nested-mutations) – Locco0_0 Apr 07 '17 at 09:16
  • No my concern is different. I already implemented the mutation in the server side. The code above works on graphiql. I want to know now how to do it on the client side using apollo / gql. – thevinci Apr 07 '17 at 13:59

1 Answers1

0

You can create different variables for your mutation, for example:

import gql from 'graphql-tag'

export const addNewStaffMutation = gql`
  mutation addNewStaff(
    $firstName: Sting!, 
    $lastName: String!,
    ...
    $positionId: number!, 
    $divisionId: number!, 
    ...
  ) {
  createStaff(input: {
    first_name: $firstName
    last_name: $lastName
    nickname: "Nname"
    positionId: $positionId
    divisionId: $divisionId
    contact_numbers: [
      {number: "66643535"}
      {number: "876876867"}
    ]
    emails: [
      {address: "testuser@gmail.com"}
      {address: "gfdsaasd@gmail.com"}
    ]
    office_location: "OP" 
  }) {
    id
    first_name
    last_name
  }
}
`

I've only replaced some of your arguments for the example, as your payload is quite big.

Then you can just build your react component and pass all the variables. You can read more about it and see some examples on Apollo Mutations.

jonschlinkert
  • 10,872
  • 4
  • 43
  • 50
Marco Daniel
  • 5,467
  • 5
  • 28
  • 36