React Native Fetch Example - Currency Exchange Rate

React Native Fetch Example - Currency Exchange Rate

Fetch Example

Introduction

In most of the mobile apps we create we will be performing calls to API's to interact with data.

one way of achieve this is by using the Fetch API see details of Fetch here:

In this example we will create a simple app that will demonstrate the use of Fetch method to retrieve information from an API.

the purpose is to get the current exchange rate between EUR, USD & GBP from an API.

for this example we will consume and open API called ratesapi.io

See API documentation here

Creating our project We will be implementing this example with TypeScript so we need to create a basic react project and then do the necessary changes to enable use of TypeScript in our project as described here

in order to speed up the process we can download a default template project already converted to TypeScript here:

Adding Code We will add our code in App.tsx replacing the default template content.

first we need to add imports for the components that we will be using at the top of the page.

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

We will define a set of types for the response of our API.

the response of the API call will be a JSON as below

{"base":"EUR","rates":{"USD":1.1741,"GBP":0.90915},"date":"2020-10-16"}

So we will define the required types to acomodate this response.

type currentExchange = {
  base: string;
  date: string;
  rates: rates;
};
type rates = {
  GBP: number;
  USD: number;
};

We will use the State to store the information retrieved from the API call so we can then use it in our render method to be displayed.

for this purpose we define an IState object curexch that will be of type currentExchange defined above.

interface IState {
  curexch: currentExchange | null;
}

In our App class we will create a method to perform the API call.

here is where we will use Fetch to do a request and store the response JSON in our state variable

public getCurExFromApi = () => {
    fetch('https://api.ratesapi.io/api/latest?symbols=USD,GBP')
      .then((response) => response.json())
      .then((json: currentExchange) => {
        this.setState({curexch: json});
      })
      .catch((error) => {
        console.error(error);
      });
  };

This method will be called in the lifecycle method componentDimMount to load the data when the component has been mounted.

public componentDidMount() {
    this.getCurExFromApi();
  }

Finally we will display the response information from the state in our render method making use of some react common components like Views & Text components.

here we can see how we check if the state already contains data before we display the information,

in case the call takes time to get the response we will display an activity indicator until the information is stored in the state.

render() {
    return this.state.curexch === null ? (
      <ActivityIndicator />
    ) : (
      <View style={styles.container}>
        <View>
          <Text style={styles.headerText}>
            Base Currency: {this.state.curexch.base}
          </Text>
        </View>
        <View style={styles.ShapeView}>
          <Text style={styles.rates}>USD: {this.state.curexch.rates.USD}</Text>
          <Text style={styles.rates}>GBP: {this.state.curexch.rates.GBP}</Text>
        </View>
      </View>
    );
  }

Below we have the whole App.tsx file content including styles (entire working project can be downloaded here

import React, {Component} from 'react';
import {View, Text, StyleSheet, ActivityIndicator} from 'react-native';
interface IState {
  curexch: currentExchange | null;
}
type Props = null;
type currentExchange = {
  base: string;
  date: string;
  rates: rates;
};
type rates = {
  GBP: number;
  USD: number;
};
export default class App extends Component<Props, IState> {
  constructor(props: Props) {
    super(props);
    this.state = {curexch: null};
  }
  public componentDidMount() {
    this.getCurExFromApi();
  }
  public getCurExFromApi = () => {
    fetch('https://api.ratesapi.io/api/latest?symbols=USD,GBP')
      .then((response) => response.json())
      .then((json: currentExchange) => {
        this.setState({curexch: json});
      })
      .catch((error) => {
        console.error(error);
      });
  };
  // renders the content for the app
  render() {
    return this.state.curexch === null ? (
      <ActivityIndicator />
    ) : (
      <View style={styles.container}>
        <View>
          <Text style={styles.headerText}>
            Base Currency: {this.state.curexch.base}
          </Text>
        </View>
        <View style={styles.ShapeView}>
          <Text style={styles.rates}>USD: {this.state.curexch.rates.USD}</Text>
          <Text style={styles.rates}>GBP: {this.state.curexch.rates.GBP}</Text>
        </View>
      </View>
    );
  }
}
// CSS styles used
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    borderColor: '#C8C8C8',
    backgroundColor: '#000000',
  },
  headerText: {
    fontSize: 30,
    textAlign: 'center',
    margin: 10,
    color: '#C8C8C8',
    fontWeight: 'bold',
  },
  rates: {
    top: 90,
    left: 60,
    fontSize: 25,
    color: '#C8C8C8',
  },
  ShapeView: {
    width: 270,
    height: 270,
    borderRadius: 4,
    borderWidth: 10,
    borderColor: '#C8C8C8',
    backgroundColor: '#000000',
  },
});
​

Now we can go ahead and execute our project in emulator to see the effect.

We will navigate to our project folder in CMD and run:

npx react-native start

this will start our Metro server

image.png

Make sure android studio is open

Open a new CMD leaving metro server window running and navigate to the project folder, there run the below command to build and run the application

npx react-native run-android

This will build the app and deploy it to emulator,

image.png

and we should see the below:

image.png

Fetch is the basic way of calling API's but there are a lot of libraries specific to perform API calls,

like:

Download an example of API call using axios implemented with functional components and useEffect hook here: