Joseph Jude

Consult . Code . Coach

Invoking external API from React Native using Fetch


code . nodejs . rn . react

This is the 5th post in the series of Learn React Native.

So far we have learned to:

External API with Fetch

We are building this tutorial on top of the earlier ones. In this tutorial, we will invoke an external API and display the result.

We will invoke PostCodes.io, which provides post-codes and geo-locations for places in the UK. I chose this API mainly because you can invoke it without any authentication.

We will use fetch network API to invoke post code API from React Native. We will use async/await to invoke the API and wait for it to return results. It goes like this:

async fetchPostCode() {
    let response = await fetch('https://api.postcodes.io/random/postcodes');
    let responseJson = await response.json();
    console.log(responseJson['result']['postcode'])
}

PostCode returns responses in json format. The response contains two values—status and result. result contains all the values that you can use. The full result looks like this:

{
    "status": 200,
    "result": {
        "postcode": "ST7 3AD",
        "quality": 1,
        "eastings": 383267,
        "northings": 354971,
        "country": "England",
        "nhs_ha": "West Midlands",
        "longitude": -2.25131080036334,
        "latitude": 53.0916865648045,
        "european_electoral_region": "West Midlands",
        "primary_care_trust": "North Staffordshire",
        "region": "West Midlands",
        "lsoa": "Newcastle-under-Lyme 003C",
        "msoa": "Newcastle-under-Lyme 003",
        "incode": "3AD",
        "outcode": "ST7",
        "parliamentary_constituency": "Stoke-on-Trent North",
        "admin_district": "Newcastle-under-Lyme",
        "parish": "Kidsgrove",
        "admin_county": "Staffordshire",
        "admin_ward": "Butt Lane",
        "ccg": "NHS North Staffordshire",
        "nuts": "Staffordshire CC",
        "codes": {
            "admin_district": "E07000195",
            "admin_county": "E10000028",
            "admin_ward": "E05006966",
            "parish": "E04008948",
            "parliamentary_constituency": "E14000973",
            "ccg": "E38000126",
            "nuts": "UKG24"
        }
    }
}

We will display postcode and region from this result.

In Creating a Custom Component tutorial, we used props to pass values to the component. If a value is available at the time of creating of a component, we can use props. But props is immutable. So how do you pass values, like the result of network API, which are available after creating the component?

state is a complimentary concept to props. Whenever you want to change a value after creating the component, you set it via state. The usual pattern for setting values via state is to create the component with default values and then whenever the values change, use setState to modify the values.

In our case, we will create the component and in the constructor, we will set default values.

constructor(props) {
super(props);
this.state = {
  postCode: 0,
  region: ''
}
}

Then when the values are available, as a result of invoking postcode API, modify the values using setState like the below:

let response = await fetch('https://api.postcodes.io/random/postcodes');
let responseJson = await response.json();
this.setState({
postCode: responseJson['result']['postcode'],
region: responseJson['result']['region']
})

For reference the full code is here:

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


export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      postCode: 0,
      region: ''
    }
  }

  async fetchPostCode() {
    try {
      let response = await fetch('https://api.postcodes.io/random/postcodes');
      let responseJson = await response.json();
      this.setState({
        postCode: responseJson['result']['postcode'],
        region: responseJson['result']['region']
      })
    } catch (err) {
      console.log(err);
    }

  }
  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity style={styles.button} onPress={() => { this.fetchPostCode() }}>
          <Text>Click Me</Text>
        </TouchableOpacity>
        <Text>Postcode: {this.state.postCode}</Text>
        <Text>Region: {this.state.region}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  button: {
    backgroundColor: '#859a9b',
    borderRadius: 20,
    padding: 10,
    marginBottom: 20,
    shadowColor: '#303838',
    shadowOffset: { width: 0, height: 5 },
    shadowRadius: 10,
    shadowOpacity: 0.35,
  },
});

In this tutorial we learned to invoke external APIs using Fetch network API and modify values using state.

This is part of Learn React Native series.

Want to learn React Native? Subscribe using the below form.


Like the post? Retweet it. Got comments? Reply.

Invoking external API from React Native using Fetch by @jjude https://t.co/3pc68vbJfb pic.twitter.com/oeIm8W3I7I

— Joseph Jude (@jjude) November 30, 2017
Share this on: Twitter / /

Comments

comments powered by Disqus