Fetch data from API in React Native

Hi everyone, in the previous article, we discussed about lifecycle methods in react native. With that knowledge, you already have gotten basic skills to develop a simple app. In this article, we are going to discuss how to Fetch data from API in React Native.

In previous articles, you learnt only the important things in react native with examples. This time, you are going to learn to Fetch data from API in React Native along with developing an app.

Creating the App

So, let’s build a new app and name it ‘Movies’. Use “react-native init Movies” command and build the app. Then, open android folder which is inside project folder in Android Studio. Then wait sometime until all the process are finished in Android Studio.

Now open the project in VSCode. I hope you remember all these things which you learnt before.

Now we start coding.

Customizing project file structure

As we have discussed before, it’s better to have a nice file structure. Therefore, follow the instructions given below.

  1. Create a folder named ‘src’ inside project folder.
  2. Cut and paste App.js file into src folder.
  3. Now, create another folder called ‘Components’ inside src folder.
  4. Update the path to App.js in index.js file.
  5. Now, run the app.

We have done these in previous articles. When you run the app, you should get the default react-native app UI.

Now, erase all the code in App.js and start to write your own.

Creating a Header for the App

We simply created a header before. But that code wasn’t reusable. Normally, mobile apps have more than one user interface. We have to navigate among them. If we don’t make our header reusable, we will have to copy and paste the header code to all the JS files. That’s not practical and that’s not what a good developer do. Therefore, we have to create a separate JS file for header and import it into App.js.

Therefore, create a JS file inside Components folder and name it Header.js. I don’t hope to use state or lifecycle methods inside Header.js file. Therefore, I am not going to need a class based component. I am creating a functional based components inside Header.js. Type the following code in Header.js.

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

const Header = () => {
    return (
        <View style={styles.viewStyle}>
            <Text style={styles.textStyle}>Movies!</Text>
        </View>
    );
}

const styles = {
    viewStyle: {
      backgroundColor: '#04A5FA',
      justifyContent: 'center',
      alignItems: 'center',
      height: 60,
      paddingTop: 15,
      shadowColor: '#000',
      shadowOffset: { width: 0, height: 2 },
      shadowOpacity: 0.2,
      elevation: 2,
      position: 'relative'
    },
    textStyle: {
      fontSize: 20,
      fontWeight: 'bold'
    }
  }
  
  export default Header;

Here, we have used only Text and View tags. Therefore, I have only imported those. I named the functional based component ‘Header’ and exported it. I named the text in the Header ‘Movies’. I have added styles as well.

Now, import it in App.js as given below.

import React, {Component} from 'react';
import { View } from 'react-native';
import Header from './Components/Header';

class App extends Component {
  render() {
    return (
      <View>
        <Header/>
      </View>
    );
  }
}

export default App;

As you can see, I have only imported View tag from react-native library. And I have imported Header component from Header.js file. When we import a js file in react native, we don’t need to add ‘.js’ extension at the end. React Native identifies it as a JavaScript file automatically. That’s why we import it like this.

import Header from './Components/Header';

And we have added Header component as a JSX element inside View tag. Run the app now and you should get the following UI.

Workflow of developing the app

Now here is what we are going to do. We are going to fetch some data from an API I created and display it nicely below the header.

I am going to create a separate JS file for data fetching section. Therefore, I am creating another JS file inside Components folder and name it ‘DataList.js’.

Now let’s code in DataList.js.

I am going to need React Native State and Lifecycle methods in this file. So, I am creating a class based component.

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

class DataList extends Component {
    render() {
      return (
        <View>
          
        </View>
      );
    }
  }
  
  export default DataList;

Fetch data from API in React Native

To Fetch data from API in React Native, we have lots of functions such as axios, fetch and so on. This time we are going to use ‘fetch’ function. The format of the fetch function is like this.

fetch('URL of the API', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                variable: value
            })

        }).then((response) => response.json())
            .then((responseJson) => {
               // Some Code if fetching is successful
            }).catch((error) => {
	       // Some Code if fetching is failed
            });

Fetch function helps us to send data to the API as well as get data from API. In the body section of above code, it converts data into json format and send it the URL of the API given inside parentheses. In this app we are creating now, we are not going to send data. We are just going to get data. API is already created and it has data in it. This is the URL for it. Since we are not going to send data, following code of fetch function is enough.

fetch(URL of the API)
            .then((response) => response.json())
            .then((responseJson) => {
                // Some Code if fetching is successful
            }).catch((error) => {
                // Some Code if fetching is failed
            });

This is how we Fetch data from API in React Native. We have to give the URL of the API inside parentheses and get the output into ‘responseJson’ variable. If data fetching is failed, we have an option called ‘catch’ for error handling.

Creating a helping method

To add this fetch method to the class based component, I need the help of a method called helping method. Helping method is something you can create only inside a class based component to help us add an reusable code inside a class based component. Whenever we need that code, we just have to call the helping method. Here is how we write helping method.

helpingMethod(){
    ...
}

You can give your helping method any name. I am going to name it ‘fetchMovies’. So, let’s add our fetch method inside helping method and fetch data as given below.

fetchMovies(){
        fetch('https://5cc814182dcd9d0014768ba9.mockapi.io/movies')
            .then((response) => response.json())
            .then((responseJson) => {
                console.log(responseJson);
            }).catch((error) => {
                console.log("Data fetching failed");
            });
    }

Calling the helping method

Here, we fetch the data and show them in console using “console.log” code. But we can’t get an output from this yet because we haven’t called the helping method. So, create the lifecycle method ‘componentWillMount()’ and call the helping method inside it as given below.

componentWillMount(){
        this.fetchMovies();
    }
componentWillMount() method will be called automatically just before the component is rendered to the screen as we learnt in last tutorial. Here is the code of DataList.js until now.
import React, {Component} from 'react';
import { View, Text } from 'react-native';

class DataList extends Component {

    fetchMovies(){
        fetch('https://5cc814182dcd9d0014768ba9.mockapi.io/movies')
            .then((response) => response.json())
            .then((responseJson) => {
                console.log(responseJson);
            }).catch((error) => {
                console.log("Data fetching failed");
            });
    }

    componentWillMount(){
        this.fetchMovies();
    }

    render() {
      return (
        <View>
          <Text>Some text</Text>
        </View>
      );
    }
  }
  
  export default DataList;

This code shows how to Fetch data from API in React Native. Here, I have added a text “Some text” to the code because I didn’t want to leave the View tag empty. Now, we have to import the DataList.js file into App.js file.

import React, {Component} from 'react';
import { View } from 'react-native';
import Header from './Components/Header';
import DataList from './Components/DataList';

class App extends Component {
  render() {
    return (
      <View>
        <Header/>
        <DataList/>
      </View>
    );
  }
}

export default App;

As you can see, I imported the DataList.js file into App.js file. Now reload the app. To realod the app in emulator you have to double tap ‘R’. If you are using a test mobile device, you can shake the device and you will get a window asking some options. Press ‘Reload’ and app will be refreshed.

New UI

I know what you are thinking. Although we fetched data, those data hasn’t been appeared in the UI. We can only see “Some text” we typed. That’s because we didn’t do anything to show those data in the UI. What we did was fetching data and showing them in the console. Let’s open the console and check whether data has been fetched correctly.

Opening console of a mobile app

To open the console of the mobile app in emulator, press Ctrl+M and you will get a window. Press “Debug js remotely”. In test mobile devices, shake your device and you will get the same window. Then, press “Debug js remotely”.

You will see one of your browser tabs open automatically as given below.

Debug JS remotely UI

Right click on the body of the tab and go to ‘Inspect’. You will see something almost similar to following image.

Inspect

There, go to Console.

Go to console

You will see something like given below.

Console window

Click on the arrow head as given below.

Console Window

Now you will see the data we fetched.

Fetched data from API

As you can see, we have successfully fetched the data from API and shown in console.

Now, you have obtained the knowledge to Fetch data from API in React Native. Now we just have to show these data in the app. We are going to discuss that part in the next article.

Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *