简体   繁体   中英

Apollo Graphql mutation with dynamic number of email address

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?

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 .

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