Reputation: 3131
I read documentation about Apollo graphql client
but still have some questions combining Apollo
and react
.
Consider, we have simple form with 4 fields with submit button. Once submit is pressed, values from the fields are saved to this.state.data
(double checked that this is saved correctly).
On the backend, I have a mutation
like: userCreate(input: UserInput): User
which definetly takes this field inputs.
The problem is:
How to execute mutation properly binding values from a
this.state.data
fields?
As of this moment I have following code:
onChange = e =>
this.setState({
data: { ...this.state.data, [e.target.id]: e.target.value }
});
handleSubmit = async () => {
writeToLog(this.state.data)
const { name, email, externalId, userCode} = this.state.data
this.props.userCreateQuery({
input: {
name,
email,
externalId,
userCode
}
})
}
this is how mutation looks like:
const QUERY_PERSON_MUTATION = gql`
mutation userCreateQuery($name: String!, $email: String!, $externalId: String!, $userCode: String!) {
userCreate(input: {
Name: $name,
Email: $email,
ExternalId: $externalId,
UserCode: $userCode}) {
Name
Email
ExternalId
UserCode
}
}`;
component wrapup:
const NewUserFormWithData = graphql(QUERY_PERSON_MUTATION, { name: 'userCreateQuery' })(NewUserForm);
export default withApollo(NewUserFormWithData)
UPDATE 1:
Schema:
const typeDefs = `
type User {
UserId: Int
/* other fields */
}
input UserInput {
UserId: Int
UserCode: String
/* other fields */
}
type Mutation {
userCreate(input: UserInput): User
userUpdate(userId: Int, input: UserInput): User
}`;
Upvotes: 1
Views: 736
Reputation: 2753
You have to use your data inside the variables key:
this.props.userCreateQuery({
variables: {
input: {
name,
email,
externalId,
userCode
}
}
})
PS.: I do not know your graphql server, but you maybe not use the key input to your mutation works.
What about we've discussed:
Your mutation with the key input.
const QUERY_PERSON_MUTATION = gql`
mutation userCreateQuery($name: String!, $email: String!, $externalId: String!, $userCode: String!) {
userCreate(
Name: $name,
Email: $email,
ExternalId: $externalId,
UserCode: $userCode) {
Name
Email
ExternalId
UserCode
}
}`;
this.props.userCreateQuery({
variables: {
name,
email,
externalId,
userCode
}
})
Upvotes: 1