React Native Networking – How To Perform API Requests In React Native using the Fetch API

As a mobile app developer, you‘ll often need to integrate data from external sources into your React Native apps. APIs, or application programming interfaces, enable this by allowing your app to exchange data securely with backend systems and databases.

For example, consider a restaurant app that lets users browse the menu and place an order. The app likely needs to pull the menu data from the restaurant‘s database and submit orders to their order processing system. APIs make this possible.

Some other common API use cases in mobile apps include:

  • Social media integration for features like activity feeds and friend lists
  • Payment processing for in-app purchases and transactions
  • Live data like weather, news, sports scores, stock quotes, etc.
  • Saving app preferences and settings to the cloud
  • Managing user accounts and subscriptions

In this tutorial, we‘ll learn how to interact with APIs in React Native using the built-in Fetch API. I‘ll show you how to make HTTP GET, POST, PUT and DELETE requests to perform actions like retrieving, creating, updating and deleting data.

Prerequisites

To follow along with this tutorial, you should have a basic understanding of React Native already. We‘ll be using the online Expo Snack environment, so make sure you have that set up. Let‘s get started!

Setting up the project

First, let‘s initialize a new React Native project in Expo Snack:

  1. Go to https://snack.expo.dev/
  2. Click "New Snack" and select the "Blank" template
  3. Open the App.js file and clear out the boilerplate code

We‘ll import the React basics we need as well as a few core components:

import React, { useState, useEffect } from ‘react‘;
import { Text, View, StyleSheet } from ‘react-native‘;

Next define the main App component. We‘ll set up some initial state to store the data fetched from the API:

export default function App() {

  const [posts, setPosts] = useState([]);
  const [isLoading, setLoading] = useState(true);

  return (
    <View style={styles.container}>
      <Text>BlogPost App</Text>
    </View>
  );
}

Here we‘re using the useState hook to create two state variables:

  • posts: an array to store the blog posts fetched from the API
  • isLoading: a boolean to keep track of when the API request is in progress

For now, the component just renders a simple title. We‘ll flesh this out soon to display the fetched posts.

The JSONPlaceholder API

For this tutorial, we‘ll use JSONPlaceholder as the API to test with. JSONPlaceholder is a free online fake REST API that you can use whenever you need some fake data. It‘s great for tutorials like this.

Specifically, we‘ll work with the /posts endpoint which lets you simulate a blogging app. It provides 100 sample blog posts which you can retrieve, add to, modify, or delete.

Here‘s a partial example of what the post data looks like:

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  ...
]

As you can see, each post is an object with a userId, id, title and body. The API supports the standard CRUD actions via HTTP methods:

  • Create post: POST /posts
  • Read post: GET /posts/:id
  • Update post: PUT /posts/:id
  • Delete post: DELETE /posts/:id

Let‘s see how to perform each of these in React Native.

Making a GET request

The most common type of API request is GET, which retrieves data from the server. To fetch the array of blog posts from the /posts endpoint:

  1. Add this code inside the App component:
  useEffect(() => {
    fetch(‘https://jsonplaceholder.typicode.com/posts‘)
      .then((response) => response.json())
      .then((json) => setPosts(json))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));
  }, []);

Here‘s what‘s happening:

  • We use the useEffect hook to perform the API call when the component mounts. The empty [] dependency array means this will only run once.

  • Inside, we use the Fetch API‘s fetch function to make a GET request to the /posts URL. This returns a Promise that resolves to the Response object.

  • We call the .json() method on the response to parse the JSON data. This also returns a Promise.

  • Once the JSON is parsed, we update the posts state variable to the array of posts using the setPosts function. If there‘s an error, we log it to the console.

  • Finally, we set isLoading to false since the request is complete.

  1. Update the component‘s JSX to render the posts:
return (
  <View style={styles.container}>
    <Text style={styles.heading}>Blog Posts</Text>

    {isLoading ? (
      <Text>Fetching posts...</Text>
   ) : (
      posts.map((post) => (
        <View key={post.id} style={styles.post}>
          <Text style={styles.title}>{post.title}</Text>
          <Text>{post.body}</Text>  
        </View>
      ))
   )}

  </View>
);

Breaking this down:

  • We display a "Fetching posts…" message while isLoading is true (i.e. the GET request is still in progress).

  • Once isLoading becomes false, we use map() to loop through the posts array and render each one. The key property is set to the unique post.id.

  • For each post, we display its title in bold and the body text below it.

  1. Finally, add some styles to make it look nicer:
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: ‘#fff‘,
    alignItems: ‘center‘,
    justifyContent: ‘center‘,
    paddingTop: 40,
  },
  heading: {
    fontSize: 24,
    fontWeight: ‘bold‘, 
    marginBottom: 20,
  },
  post: {
    borderBottomWidth: 1,
    borderBottomColor: ‘#ccc‘,
    paddingVertical: 20,
  },
  title: {
    fontSize: 18,
    fontWeight: ‘bold‘,
    marginBottom: 10,
  },  
});

And with that, you should see the blog posts displayed in your app! The initial "Fetching posts…" is quickly replaced by the post list as soon as the GET request completes.

This is the most basic way to fetch data from an API in React Native. But the Fetch API can do much more. Let‘s look at the other request methods.

Making a POST request

To add a new blog post to the API, we can make a POST request to the same /posts endpoint. The difference is we‘ll need to include the post data in the request body. Here‘s how:

fetch(‘https://jsonplaceholder.typicode.com/posts‘, {
  method: ‘POST‘,
  headers: {
    Accept: ‘application/json‘,
    ‘Content-Type‘: ‘application/json‘,
  },
  body: JSON.stringify({
    userId: 1,
    title: ‘My New Post‘,
    body: ‘Hello world!‘,  
  }),
})
  .then((response) => response.json())
  .then((json) => console.log(json));

The key parts:

  • Specify method: ‘POST‘ to change the request method from the default GET
  • Include Accept and Content-Type headers to indicate we‘re sending and receiving JSON data
  • Add a body property with an object containing the new post data. Convert it to a JSON string with JSON.stringify

If successful, this will return a response containing the newly created post object, including a unique id assigned by the server:

{
  "userId": 1,
  "title": "My New Post",
  "body": "Hello world!",
  "id": 101
}

Of course, the JSONPlaceholder API isn‘t actually saving this post persistently. But this is how you‘d structure a real POST request.

Making a PUT request

To update an existing blog post, make a PUT request to the /posts/:id endpoint, specifying the post‘s id. Include the updated post fields in the body:

fetch(‘https://jsonplaceholder.typicode.com/posts/1‘, {
  method: ‘PUT‘,
  headers: {
    Accept: ‘application/json‘,
    ‘Content-Type‘: ‘application/json‘,
  },
  body: JSON.stringify({
    title: ‘Updated Title‘,
    body: ‘Updated body text‘,
  }),
})
  .then((response) => response.json())
  .then((json) => console.log(json));

This will "update" the post with id: 1, replacing its title and body with the values specified. The server responds with the updated post object.

Making a DELETE request

Finally, to remove a post from the API, make a DELETE request to /posts/:id:

fetch(‘https://jsonplaceholder.typicode.com/posts/1‘, {
  method: ‘DELETE‘,
});

No request body is needed, just the method and post id. The server will respond with a 200 OK status if the delete succeeds.

Integrating Other APIs

Once you‘re comfortable with the Fetch API basics, you can start integrating other APIs into your React Native apps. There are public APIs available for all kinds of data and services. Some popular options:

  • Social media: Facebook, Twitter, Instagram, LinkedIn
  • Payment processing: Stripe, PayPal, Square
  • Maps: Google Maps, Mapbox
  • Weather: OpenWeather, WeatherAPI
  • News: NewsAPI, Currents API
  • Crypto prices: CoinGecko, CryptoCompare

The general process is the similar for any API:

  1. Read the API documentation
  2. Sign up for an API key if required
  3. Construct the URL with query parameters
  4. Choose the appropriate request method
  5. Make the request with fetch, handling the Promise response
  6. Update your app state and UI with the returned data

Conclusion

Congratulations, you now know how to use the Fetch API to integrate data from APIs into your React Native apps! I hope this tutorial demystified the process of making GET, POST, PUT and DELETE requests.

APIs open up a whole world of data possibilities for your apps. So go exploring and see what you can build. Happy coding!

Similar Posts