'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: "[email protected]"}
{address: "[email protected]"}
]
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?
Solution 1:[1]
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: "[email protected]"}
{address: "[email protected]"}
]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | jonschlinkert |