How to use Fetch API with React Native?

•

Fri Apr 14 2023

•

5 min read

React Native is a popular framework for developing native mobile apps with JavaScript and React. When developing mobile apps, it's common to make network requests to retrieve data from a server or API.

This is where the Fetch API comes in; it's a modern JavaScript API for making API requests supported by most modern browsers and environments, including React Native.

Getting started

To get our React Native project up and running, we'll use the Expo CLI. Expo CLI is a command-line interface for creating, developing, and deploying React Native apps.

Step #1

Install Node.js and npm on your computer. You can download the installer from here.

Step #2

Open a command prompt or terminal window and run the following command:

sh
npx create-expo-app@latest --example with-router

Step #3

Create a new folder and make an index.js and _layout.js file in it. Add the following code in your _layout.js file:

js
import { Stack } from "expo-router";
export default function Layout() {
return <Stack />;
}

Step #4

Once you’ve created these files, install Axios by running this command:

sh
npm install axios

Start the development server by running the following command:

sh
npm start

You will see something like this in your terminal:

You need to download Expo Go from the app store or play store to view your application. Scan the QR code you see in your terminal from your camera or Expo Go application.

This might not apply to everyone, but you might see this error the first time you open your application:

To solve this, simply run the following command to globally install the expo-cli package, which is used to run our application:

sh
npm install -g install expo-cli

Once it is installed, run this command:

sh
expo-cli start -- tunnel

Now you will be able to see your expo react native application on your phone.

Making API requests using Fetch API

Now let's dive into making API requests using Fetch API in a React Native component.

When using Fetch API in a React Native component, the first step is to import the API endpoint you want to retrieve data from. You can do this using the fetch() method, a global method available in all modern browsers and environments, including React Native.

Here's an example of how to use Fetch API to make a GET request to an API endpoint:

js
fetch('https://my-api.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

It's important to note that fetch() returns a Promise, which means you can use async/await syntax to make your code more readable and avoid callbacks. Here's an example of how to do this:

js
async function fetchData() {
try {
const response = await fetch('https://my-api.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
fetchData();

Demo

In the index.js file you created earlier, we'll now write our code for fetching the data. For this example, we'll be using the Quotes API by API Ninjas from the Rapid API hub.

Loading component...
js
import React, { useState, useEffect } from 'react';
import { View, Text } from 'react-native';
const App = () => {
const [quote, setQuote] = useState('');
useEffect(() => {
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': 'cee3bd1e22msheedb98e87dec740p196316jsn6d22f5917037',
'X-RapidAPI-Host': 'quotes-by-api-ninjas.p.rapidapi.com'
}
};
fetch('https://quotes-by-api-ninjas.p.rapidapi.com/v1/quotes', options)
.then(response => response.json())
.then(data => setQuote(data[0].quote))
.catch(error => console.error(error));
}, []);
return (
<View>
<Text>{quote}</Text>
</View>
);
};
export default App;

You will see something like this on your application:

We created a React Native component that fetches a random quote from the Quotes by API Ninjas API using the fetch() function, sets it using useState(), and displays it in a Text component. The useEffect() hook ensures that the API is only called once when the component is mounted.

Add styling

You can add some styles to your application by adding a StyleSheet component.

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

Then add the following styles in your index.js file:

js
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center,'
backgroundColor: '#F5FCFF',
},
quoteText: {
fontSize: 24,
fontStyle: 'italic',
textAlign: 'center',
marginHorizontal: 20,
},
});

You can modify these styles to suit your needs and create a more visually appealing app. This is how your application would look with a little bit of styling:

Wrap up

The Fetch API provides a straightforward way to make API requests in React Native. We demonstrated how to use the Fetch API to make requests to the Quotes by API Ninjas API and display a random quote using a simple React Native component.

We have also written a similar guide on how to use Fetch API with Axios, which you can read here.