Updated May 29, 2019

Apollo Setup Kickstart

App.js

import React from 'react';
import {
  StyleSheet,
  SafeAreaView,
  FlatList,
  View,
  Text,
  TouchableOpacity,
} from 'react-native';
import { createStackNavigator, createAppContainer } from 'react-navigation';
import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { HttpLink } from 'apollo-link-http';
import gql from 'graphql-tag';
import { ApolloProvider, Query } from 'react-apollo';

const cache = new InMemoryCache();
const link = new HttpLink({
  uri: 'https://countries.trevorblades.com/',
});
const client = new ApolloClient({
  cache,
  link,
});

const styles = StyleSheet.create({
  row: {
    backgroundColor: '#fff',
    paddingVertical: 10,
  },
  text: {
    color: '#4a4a4a',
    fontSize: 15,
    paddingHorizontal: 10,
    paddingVertical: 10,
  },
  separator: {
    flex: 1,
    height: 1,
    backgroundColor: '#e4e4e4',
    marginLeft: 10,
  },
});

const GET_LIST = gql`
  query list {
    countries {
      code
      name
    }
  }
`;

class List extends React.Component {
  // state = {
  //   countries: [],
  // };

  // componentDidMount() {
  //   client.query({
  //     query: gql`
  //       query list {
  //         countries {
  //           code
  //           name
  //         }
  //       }
  //     `
  //   })
  //   .then(response => {
  //     console.log('response', response);
  //     this.setState({ countries: response.data.countries });
  //   })
  // }

  render() {
    const { navigation } = this.props;
    return (
      <Query query={GET_LIST}>
        {({ data, loading, error }) => {
          if (loading || error) {
            return null;
          }

          return (
            <FlatList
              // data={this.state.countries}
              data={data.countries}
              keyExtractor={(item) => item.code}
              renderItem={({ item }) => (
                <TouchableOpacity
                  onPress={() =>
                    navigation.navigate('Details', { country: item })
                  }
                >
                  <View style={styles.row}>
                    <Text style={styles.text}>{item.name}</Text>
                  </View>
                </TouchableOpacity>
              )}
              ItemSeparatorComponent={() => <View style={styles.separator} />}
            />
          );
        }}
      </Query>
    );
  }
}

const GET_DETAILS = gql`
  query details($code: String!) {
    country(code: $code) {
      code
      name
      native
      phone
      currency
      emoji
    }
  }
`;

class Details extends React.Component {
  render() {
    const country = this.props.navigation.getParam('country', {});

    return (
      <Query query={GET_DETAILS} variables={{ code: country.code }}>
        {({ data, loading, error }) => {
          if (loading || error) {
            return null;
          }

          return (
            <View>
              {Object.keys(data.country).map((key) => (
                <Text style={styles.text} key={key}>
                  <Text style={{ fontWeight: 'bold' }}>{key}:</Text>{' '}
                  {data.country[key]}
                </Text>
              ))}
            </View>
          );
        }}
      </Query>
    );
  }
}

const Stack = createStackNavigator({
  List: {
    screen: List,
    navigationOptions: {
      headerTitle: 'Countries',
    },
  },
  Details: {
    screen: Details,
    navigationOptions: ({ navigation }) => ({
      headerTitle: navigation.getParam('country', {}).name,
    }),
  },
});

const App = createAppContainer(Stack);

export default () => (
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>
);

const data = [{ code: 'US', name: 'United States' }];
const detailData = {
  code: 'US',
  name: 'United States',
  native: 'United States',
  phone: '1',
  currency: 'USD,USN,USS',
  emoji: '🇺🇸',
};
React Native School Logo

React Native School

Want to further level up as a React Native developer? Join React Native School! You'll get access to all of our courses and our private Slack community.

Learn More