How do I do a GraphQL mutation callback?
This is how my react component and the mutation looks like:
class CreateAccount extends Component {
constructor () {
super()
this.state = {
username: '',
password: ''
}
}
render () {
return (
// form with input fields; values get stored as state
)
}
_createUser = async () => {
const { username, password } = this.state
await this.props.createUserMutation({
variables: {
username,
password
}
})
}
}
export default compose(
withData,
withApollo,
graphql(
gql`
mutation RootMutationQuery($username: String!, $password: String!) {
createUser(
username: $username,
password: $password,
) {
_id
username
password
}
}
`, { name: 'createUserMutation' }
)
)(CreateAccount)
I would suggest you use the mutation as promise and when clicking the form submit you make the request.
Be aware that a login error can be retrieved in the .catch
function. The error consists of an eventual network or graphql Error which need to be treated differently. See for example this post .
The Component could look like this:
class CreateAccount extends Component { constructor(props) { super(props); this.state = { username: '', password: '' }; } render() { return ( // form with input fields; values get stored as state // on submit is handled for the form ); } _onSubmit = (event) => { event.preventDefault(); const { username, password } = this.state; this.props.createUserMutation({ variables: { username, password } }).then(response => { // data in response.data.createUser // set state eg handle login }).catch(error => { // handle error }); } } export default compose( graphql( gql ` mutation RootMutationQuery($username: String!, $password: String!) { createUser( username: $username, password: $password, ) { _id username password } } `, { name: 'createUserMutation' } ) )(CreateAccount)
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.