0
votes

I would like to use a GraphQL API on a React-Native App with react-apollo.

My server-side API is functional. All my tests with the playground works perfectly.

On the other hand, since react-native things get complicated: how to reuse what was set up server side? (mutation in particular) Do I have to duplicate the GraphQL code?

I exported my schema graphql using CodeGen (great tool!), But how to use it on react-native ?

My config on React-Native :

const httpLink = createHttpLink({
  uri: API_GRAPHQL_URL,
  clientState: {
    typeDefs
  }
});

const getToken = async () => await AsyncStorage.getItem('userToken');

const authLink = setContext(async (_, { headers }) => {
  const token = await getToken();

  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : ''
    }
  };
});

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
});

My typeDefs is schema exported on CodeGen, for example :

enter image description here

But, how use Mutation with my exported configuration ? I use react-apollo-hooks.

The client part of GraphQL is not very clear for me, despite a great reaction-apollo documentation.

Would anyone help me or have a reference article on the subject?

Thank you so much !

1

1 Answers

0
votes

in order to reuse you can create a schema.js file and export your queries from there in to to relevant screens, with regards to Mutations here is an example of a signUp page that uses Mutation.

    import FormInput from '../components/FormInput';
    import FormButton from '../components/FormButton';
    import { useMutation } from '@apollo/client';
    import { gql } from 'apollo-boost'

 


  
const SIGNUP_USER = gql`
 mutation SignupMutation($email: String!, $password: String!, $name: String!) {
   signupWithEmail(email: $email, password: $password, name: $name) {
     user {
        email
        name
     }
   }
}`


    function SignUp (){

    export default function SignUp() {

  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");


  const [signupWithEmail] = useMutation(SIGNUP_USER);
  const navigation = useNavigation();


      const navigation = useNavigation();


    return (





    <ScrollView>

  

    <View style={{justifyContent: 'center', alignItems: 'center'}}>


        <FormInput
          style={styles.input}
          maxLength={15}
          placeholder="name"
          onChangeText={name => setName(name)}
          value={name}
        />

        <FormInput
          style={styles.input}
          placeholder="email"
          onChangeText={email => setEmail(email)}
          value={email}
          autoCorrect={false}
          keyboardType='email-address'
          autoCapitalize='none'
        />

        <FormInput
          style={styles.input}
          maxLength={15}
          secureTextEntry={true}
          placeholder="password"
          onChangeText={password => setPassword(password)}
          value={password}
        />


        <FormButton
         title="Signup"
         modeValue="contained"
         color="#2D374F"
         labelStyle={styles.loginButtonLabel}
         onPress={() => signupWithEmail({variables: {email, password, name}})}
         />




    </View>

    </ScrollView>

    );
    }

your server side resolver should look like this please note im using firebase here.

   Mutation: {

  signupWithEmail: async (_, { email, password }) => {
   const user = firebase.auth()
  .createUserWithEmailAndPassword(email, password)
  .then((userCredentials) => { return userCredentials.user.updateProfile
  ({displayName: name})
  })
   return { user }
  },

},

and your schema should look like this:

  type Mutation {
    signupWithEmail(email: String!, password: String!, name: String!): AuthPayload!
    loginWithEmail(email: String!, password: String!): AuthPayload!
  }


  type User {
    uid : ID!
    email: String!
    name: String!
  }


  type AuthPayload {
   user: User!
 }