React Native Apollo Example

React Native Apollo Example

Setup

Option 1: Do it yourself

create-react-native-app react-native-apollo-example
cd react-native-apollo-example
yarn add apollo-client-preset react-apollo graphql
# and replace below code for App.js

Option 2: Clone my repo

git clone git@github.com:tylerbuchea/react-native-apollo-example.git
cd react-native-apollo-link-state-example
yarn install && yarn start

Option 3: Check it out now with Expo

Go here or scan the QR code below:

The Code

import React from 'react';
import { Text, View, SafeAreaView } from 'react-native';

import ApolloClient from 'apollo-client';
import { HttpLink, InMemoryCache } from 'apollo-client-preset';
import { ApolloProvider, graphql } from 'react-apollo';
import gql from 'graphql-tag';

// Main App export
export default class ApolloApp extends React.Component {
  render() {
    return(
      <ApolloProvider client={client}>
        <SafeAreaView>
          <MovieDetails />
        </SafeAreaView>
      </ApolloProvider>
    );
  }
}
 
// Apollo client
const client = new ApolloClient({
  link: new HttpLink({ uri: 'https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr' }),
  cache: new InMemoryCache().restore({}),
});
 
// Example query from https://www.graph.cool/
const MOVIE_QUERY = gql`
{
  allMovies {
    title
    actors {
      name
    }
  }
}
`;
 
// MovieDetails Component
const MovieDetails = graphql(MOVIE_QUERY)(({ data }) => {
  const { loading, allMovies } = data;

  if (loading) return <View><Text>loading...</Text></View>;

  return (
    <View style={{ padding: 10 }}>
      {allMovies.map(({ title, actors }) => (
        <Text key={title}>
          {title}: {actors.map(({ name }) => name).join(', ')}
          {'\n'}
        </Text>
      ))}
    </View>
  );
});

You can play with the GraphQL server used in this in example here.

Resources