Last active
April 25, 2018 11:34
-
-
Save danielfttorres/99c46c984c9712c7882f71d17f3e01b7 to your computer and use it in GitHub Desktop.
A example of Mutation using Relay Modern and React Native
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @flow | |
import React, { PureComponent } from 'react' | |
import { View, Text, TextInput, TouchableOpacity } from 'react-native' | |
import { commitMutation, graphql } from 'react-relay' | |
import environment from './createRelayEnvironment' | |
import style from './RegisterScreen.style' | |
/** | |
* In Relay Modern a name pattern are used in Mutations or Queries, as example below: | |
* `ComponentName__MutationName__Mutation(...` | |
*/ | |
const mutation = graphql` | |
mutation RegisterScreen__RegisterEmail__Mutation( | |
$input: RegisterEmailInput! | |
) { | |
RegisterEmail(input: $input) { | |
token | |
error | |
} | |
} | |
` | |
class RegisterScreen extends PureComponent { | |
static navigationOptions = { | |
header: null, | |
gesturesEnabled: false | |
} | |
state = { | |
name: null, | |
email: null, | |
password: null | |
} | |
constructor() { | |
super() | |
this.doRegister = this.doRegister.bind(this) | |
} | |
RegisterEmailMutationSuccess({ RegisterEmail }) { | |
const { token, error } = RegisterEmail | |
// Successful. Go to the party o/ | |
} | |
RegisterEmailMutationError(error) { | |
// You can use a more sofisticated error logger :) | |
console.error('RegisterEmailMutation ::Error', error) | |
} | |
doRegister() { | |
const { name, email, password } = this.state | |
const variables = { | |
input: { | |
name, | |
email, | |
password | |
}, | |
} | |
commitMutation( | |
environment, | |
{ | |
mutation, | |
variables, | |
onCompleted: res => this.RegisterEmailMutationSuccess(res), | |
onError: err => this.RegisterEmailMutationError(err), | |
}, | |
) | |
} | |
render() { | |
const { name, email, password } = this.state | |
return ( | |
<View style={style.container}> | |
<TextInput value={name} | |
onChangeText={(name) => this.setState({ name })} | |
/> | |
<TextInput value={email} | |
onChangeText={(email) => this.setState({ email })} | |
/> | |
<TextInput value={password} | |
secureTextEntry={true} | |
onChangeText={(password) => this.setState({ password })} | |
/> | |
<TouchableOpacity onPress={this.doRegister}> | |
<Text>Register</Text> | |
</TochableOpacity> | |
</View> | |
) | |
} | |
} | |
export default RegisterScreen |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment