Newby Coder header banner

React Native App with Rest API call

Since React Native is a javascript framework, http requests can be made using fetch() function or other javascript alternatives

Provided example uses fetch() function to get data from server

Creating new React Native App

Check React Native Installation for installation related info

Use react-native init command to create a new React Native project (here named NcRestApiApp)

react-native init NcRestApiApp

This creates a directory named NcRestApiApp and initializes it as a react native application directory

This can be skipped in case an existing react native project is being integrated into


Dependency

react-native-svg package is used to display Svgs and NavigationBar to show simple text in app bar

Go to project directory (here NcRestApiApp)

cd NcRestApiApp

Add react-native-svg and react-native-navbar packages to current project using yarn

yarn add react-native-svg react-native-navbar

or using npm

npm install react-native-svg react-native-navbar --save

iOS

After yarn add command, cd into ios folder inside project directory

cd ios

Use pod command to install any required CocoaPods dependencies:

pod install

Usage

Example rest api call

fetch('https://restcountries.eu/rest/v2/all')
.then(response => response.json())
.then(responseJson => {
  console.log("response json " + JSON.stringify(responseJson.length))
})
.catch(error => {
  console.error(error);
});

It fetches a json of countries and related information from a public rest Api

fetch() is an async function whose response can be captured using then() method

Also, response of a fetch() call has an async method json() which returns the Json equivalent of the response

It was observed that catch() didn't handle some network failures

A chain of async functions can instead be made synchronous to facilitate a generic exception handling

try{
    var response = await fetch('https://restcountries.eu/rest/v2/all');
    var responseJson = await response.json();
    console.log("response json " + JSON.stringify(responseJson.length));
}
catch(error) {  console.error(error); }

App Code

Following code makes a rest Api call to fetch data of countries and renders a list of countries with their flags

Since images of these flags are in svg format, SvgUri component of react-native-svg is used to display them

Some flags show a plain color since SvgUri do not support all Svg properties and values

App.js
import React from 'react';
import {
  StyleSheet,
  View,
  Text,
  Image, FlatList
} from 'react-native';

import NavigationBar from 'react-native-navbar';
import { SvgUri } from 'react-native-svg';

import { YellowBox } from 'react-native';
YellowBox.ignoreWarnings(['#00']);


export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      serverData: [],
      counter: 1
    };
  };

  componentDidMount() {
    this.getRestApiData();
  };

  getRestApiData() {
    try {
      fetch('https://restcountries.eu/rest/v2/all')
        .then(response => response.json())
        .then(responseJson => {
          responseJson.forEach((item) => item.key = item.name);
          console.log("response json " + JSON.stringify(responseJson.length))
          this.setState({
            serverData: responseJson,
          });
        })
        .catch(error => {
          console.error(error);
        });
      }
      catch(error) { console.log("error ", error)}
  };

  renderItem(item) {
    // console.log(item.flag);
    return (
      <View key={item.name} style={styles.item}>
        <Text>{item.name}</Text>
        <View  style={styles.image}>
          <SvgUri uri={item.flag} height='40' width='40' />
        </View>
      </View>
    );
  }

  getListView(data) {
    return (
      <View style={styles.itemContainer}>
        <FlatList
          data={data}
          renderItem={({item}) => this.renderItem(item) }
          maxToRenderPerBatch='250'
        />
      </View>
    );
  };

  render() {
    const {serverData} = this.state;
    var listView = <Text> No response from server </Text>;
    if(serverData && serverData.length > 0) {
        listView = this.getListView(serverData);
    }
    return (
      <View style={{flex:1}}>
        <NavigationBar style={{ backgroundColor: '#f4511e'}} title={{title: 'App with Rest Api Call', style:{color:'white', fontWeight:'bold'} }}/>
        <View>
              {listView}
        </View>
      </View>
    );
  };
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#253',
    alignItems: 'center',
    padding: 16,
  },
  itemContainer: {
    alignItems: 'center'
  },
  item: {
    backgroundColor: 'lightblue',
    width: 400,
    padding: 10,
    margin: 2,
    flex: 1,
    flexDirection: 'row'
  },
  image: {
    position: 'absolute',
    right:20,
    alignSelf: 'center',
    resizeMode: 'contain',
    width: 40, height: 40
  }
});

Run instructions

Running in Android

cd into project directory (here NcRestApiApp)

cd NcRestApiApp

Run metro server to serve js

react-native start

Go to project directory in another terminal tab

Enter following run command for Android:

react-native run-android
cl-react-native-rest-api

Running in ios

cd into project directory (here NcRestApiApp)

cd NcRestApiApp

Enter following command :

react-native run-ios

This might take some time


If the app shows error about metro server not configured (check Running an App in iOS), then run metro server in another tab:

react-native start

Reload the app

Re-run react-native run-ios command if reloading doesn't work

cm-react-native-rest-api-as1cm-react-native-rest-api-as2cm-react-native-rest-api-as3