react native graphql simple query example using apollo

1. Add the following packages.

npm install @apollo/react-hooks apollo-boost apollo-client apollo-link-context graphql --save

2. apolloClient.js, the file that does the graphql query call to the server.

import { gql } from 'apollo-boost';
import { InMemoryCache, NormalizedCacheObject } from 'apollo-cache-inmemory';
import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';

const cache = new InMemoryCache();
const link = new HttpLink({
  uri: 'https://48p1r2roz4.sse.codesandbox.io',
});

const client: ApolloClient = new ApolloClient({
  cache,
  link
});

/**
 * Get exchange rates for a specified country currency.
 * @param country USD, CNY, JPY, CAD, GBP, etc
 */
export async function fetchExchangeRate(country: string): Promise {

  try {
    const response = await client
          .query({
            query: gql`
              {
                rates(currency: "USD") {
                  name
                  currency
                  rate
                }
              }
            `,
          });

    return response;
  } catch (error) {
      console.error(error);
      return error;
  }

}

3. Currency.js, the screen that triggers the graphql query and displays the result.

import React, { Component } from 'react';
import { ActivityIndicator, FlatList, Text, View } from 'react-native';
import { fetchExchangeRate } from './apolloClient';
import commonStyles from './common.styles.js';

export default class Currency extends Component {

  constructor(props) {
    super(props);
    this.state ={ isLoading: true, error: false }
  }

  componentDidMount() {
    this.setState({ loading: true }, async () => {
      try {
        const usdRates = await fetchExchangeRate('USD');
        console.log("componentDidMount() USD exchange rates: " + JSON.stringify(usdRates))
        this.setState({
          isLoading: false,
          dataSource: usdRates.data.rates
        });
      } catch (e) {
        this.setState({
          isLoading: false,
          error: true,
        });
      }
    })

  }

  render(){

    if (this.state.isLoading) {
      return(
        
          
        
      )
    }

    return(
      
         currency.toString()}
        />
      
    );

  }

    renderItem(item) {
        const data = item.item
        return (
            
                
                    Name: {data.name}
                
                
                    Currency: {data.currency}
                
                
                    Rate: {data.rate}
                
                
            
        )
    }


}

4. The style file common.styles.js

import { StyleSheet } from 'react-native';
export default StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
    paddingHorizontal: 10,
    paddingVertical: 20
  },
  rowItem: {
      flexWrap: "wrap",
      flexDirection: 'row',
      paddingVertical: 5
  },
  rowItemText: {
    fontSize: 12
  },
  propertyText: {
    fontFamily: 'Cochin',
    fontWeight: 'bold'
  },
  horizontalLine: {
    height: 2,
    width: '100%',
    backgroundColor: 'black'
  }
})

5. The App.js

import * as React from 'react';
import { View } from 'react-native';
import commonStyles from './common.styles.js';
import Currency from './Currency';

export default function App() {
  return (
    
      
    
  );
}

Complete example in Github

Search within Codexpedia

Custom Search

Search the entire web

Custom Search