HOW TO MAKE REST API CALLS IN REACT NATIVE

Share the post

Hello All, In the last topic, We had discussed How to get TextInput on a button click. In this topic, We will discuss How to make REST API calls in react native. In react-native applications, Communicating with server & database is possible by using HTTP requests. So, to do that we will use the fetch() function which will make the HTTP request & fetch the data for us. This tutorial will explain to you all the necessary steps required to make an HTTP request. So, let’s start.

Use fetch() method:

To make HTTP request, We will use fetch() method to do that. fetch(‘PUT YOUR URL HERE’) and handle the success & error response.

  fetch("URL HERE")  

Example to make REST API calls in react native

  1. Create a new page HomePage.js
  2. Initialize the state values as follows
state = {
        showLoading: false,
        allData: []
    }

Here we are going to use showLoading to show the loader & allData to get JSON response

3. We are using FlatList to show response in list format.

 <View style={styles.container}>

                <FlatList
                    data={this.state.allData}
                    ItemSeparatorComponent={this.ItemSeparator}
                    renderItem={item => this.renderItem(item)}
                />

                {this.state.showLoading &&
                    <View>
                        <ActivityIndicator size="large" />
                        <Text>Please wait...</Text>
                    </View>
                }
                <Button onPress={() => this.fetchValues()} title='Fetch Values' />
 </View>

In the above code, We are showing the response by using FlatList. data contains all our responses which we want to show and renderItem will call one more function called renderItem(). This function will show the individual list item. The code for the same is shown below

renderItem = (data) => {
        return (
            <TouchableOpacity>
                <Text>Name :{data.item.name}</Text>
                <Text>Username :{data.item.username}</Text>
                <Text>Address :{data.item.address}</Text>
            </TouchableOpacity>
        )

}

4. We are assigning the sample JSON data to allData which we assuming that get it through HTTP call response. The sample JSON is shown as follows

[
                        {
                            "id": 1,
                            "name": "ABC",
                            "username": "abc@mumbai",
                            "address": "Mumbai"

                        },
                        {
                            "id": 2,
                            "name": "XYZ",
                            "username": "xyz@mumbai",
                            "address": "Mumbai"

                        }
]

5. Now, We will do the network call by using fetch(). The code for the same is as shown below

 fetch("URL HERE")
            .then(response => response.json())
            .then((resultData) => {
                console.log('getting data from fetch', resultData)
                this.setState({
                    showLoading: false,
                    // allData: resultData,
                    allData: [
                        {
                            "id": 1,
                            "name": "ABC",
                            "username": "abc@mumbai",
                            "address": "Mumbai"

                        },
                        {
                            "id": 2,
                            "name": "XYZ",
                            "username": "xyz@mumbai",
                            "address": "Mumbai"

                        }
                    ]
                })
            })
            .catch(error => {
                console.log(error);
                this.setState({
                    showLoading: false,
                    allData: [
                        {
                            "id": 1,
                            "name": "ABC",
                            "username": "abc@mumbai",
                            "address": "Mumbai"

                        },
                        {
                            "id": 2,
                            "name": "XYZ",
                            "username": "xyz@mumbai",
                            "address": "Mumbai"

                        }
                    ]
                })

                
            });

In the above code, We have not included the URL. Therefore, the service not getting called. Hence, It’s going in the error section where we assign static data to allData. If you include the standard URL which gives you JSON output then this will go into the success section where you have to remove static JSON data & uncomment this line allData: resultData.

6. Full Source code for example is as shown below

import { StatusBar } from 'expo-status-bar';
import React, { Component } from 'react';
import { StyleSheet, Text, View, Button, TextInput, FlatList, ActivityIndicator, TouchableOpacity } from 'react-native';


export default class HomePage extends Component {
    state = {
        showLoading: false,
        allData: []
    }

    fetchValues = () => {

        this.setState({
            showLoading: true,
        })
        fetch("URL HERE")
            .then(response => response.json())
            .then((resultData) => {
                console.log('getting data from fetch', resultData)
                this.setState({
                    showLoading: false,
                    // allData: resultData,
                    allData: [
                        {
                            "id": 1,
                            "name": "ABC",
                            "username": "abc@mumbai",
                            "address": "Mumbai"

                        },
                        {
                            "id": 2,
                            "name": "XYZ",
                            "username": "xyz@mumbai",
                            "address": "Mumbai"

                        }
                    ]
                })
            })
            .catch(error => {
                console.log(error);
                this.setState({
                    showLoading: false,
                    allData: [
                        {
                            "id": 1,
                            "name": "ABC",
                            "username": "abc@mumbai",
                            "address": "Mumbai"

                        },
                        {
                            "id": 2,
                            "name": "XYZ",
                            "username": "xyz@mumbai",
                            "address": "Mumbai"

                        }
                    ]
                })

                
            });
    }

    ItemSeparator = () => {
        return (
            <View
                style={{
                    height: 1,
                    backgroundColor: "#000"
                }}
            />
        );
    };

    renderItem = (data) => {
        return (
            <TouchableOpacity>
                <Text>Name :{data.item.name}</Text>
                <Text>Username :{data.item.username}</Text>
                <Text>Address :{data.item.address}</Text>
            </TouchableOpacity>
        )

    }

    render() {
        return (
            <View style={styles.container}>

                <FlatList
                    data={this.state.allData}
                    ItemSeparatorComponent={this.ItemSeparator}
                    renderItem={item => this.renderItem(item)}
                />

                {this.state.showLoading &&
                    <View>
                        <ActivityIndicator size="large" />
                        <Text>Please wait...</Text>
                    </View>
                }
                <Button onPress={() => this.fetchValues()} title='Fetch Values' />
            </View>
        );
    }

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        padding: 50
    },

});


     

7. The output for above code is as shown below

Output
Output

This is the simple example which gives you an idea about how to call HTTP requests in react native.

1 thought on “HOW TO MAKE REST API CALLS IN REACT NATIVE”

Leave a Comment