Comprehensive Guide to APIs in React Native

React Native stands out as a popular frontend library for developers aiming to build applications. For the development of production-ready apps, integrating APIs into React Native applications becomes inevitable.

Developers aspiring to construct modern, robust web applications using React Native must grasp the fundamentals of consuming APIs to fetch data. This beginner's guide walks you through the process of consuming RESTful APIs in React Native, covering data fetching, deletion, and addition. It delves into the two primary approaches for consuming RESTful APIs and demonstrates their utilization with React Native hooks.

What is a REST API?

REST, defined by Roy Fielding in 2000, is an architectural style commonly used in developing internet services. REST stands for "REpresentational State Transfer," and it enables applications to communicate programmatically, returning real-time responses. Requests to a REST API send a representation of the resource's current state, often in formats like JSON, XML, or HTML. JSON, being language-independent and readable by both humans and machines, is the most widely used format.

How to Consume REST APIs in React Native

Consuming REST APIs in React Native can be approached in various ways. This guide focuses on two popular methods: Axios (a promise-based HTTP client) and Fetch API (a browser in-built web API). Prior familiarity with JavaScript, React Native, and React Native hooks is essential for a comprehensive understanding of the guide.

When working with React Native, API requests differ from traditional JavaScript approaches, as these requests are now handled within React Native components. Functional components, particularly using two key React Native hooks, become essential:

  1. useEffect Hook: In React Native, API requests are often performed within the useEffect() hook, rendering either immediately upon app mount or after reaching a specific state.
    useEffect(() => {
        // data fetching here
    }, []);
  2. useState Hook: When fetching data, a state is needed to store the returned data. The data can be stored in a state management tool like Redux or in a React Native local state.
    const [posts, setPosts] = useState([]);

Let's now get into the meat of this guide, where we'll learn how to get, add, and delete data. This knowledge is applicable to any type of API, as this guide is intended for beginners.

Difference between fetch and axios

Axios and Fetch API are both ways to make HTTP requests in JavaScript, but they have some differences in their syntax, features, and browser compatibility. Here are some of the main differences:

  • Axios is a third-party library that you need to install, while Fetch API is a native web API that is built into modern browsers.
  • Axios automatically converts the data to JSON format, both for sending and receiving, while Fetch API requires you to manually stringify the data for sending and parse the data for receiving.
  • Axios has built-in protection against cross-site request forgery (XSRF) attacks, while Fetch API does not.
  • Axios allows you to set a timeout for the requests, cancel the requests, and intercept the requests and responses, while Fetch API does not have these features by default.
  • Axios supports the progress event for tracking the upload and download progress, while Fetch API only supports the download progress.
  • Axios has wider browser support than Fetch API, as it works with older browsers like IE11, while Fetch API only works with newer browsers like Chrome, Firefox, Edge, and Safari.

Using Fetch and axios in React Native

Working with APIs in React Native involves making requests to the API endpoints, processing the responses, and rendering the data in the app’s UI. APIs are essential for React Native development, as they allow you to access data and functionality from your own server or third-party services.

There are different ways to make API requests in React Native, but two of the most popular approaches are using Axios and Fetch API. Axios is a promise-based HTTP client that has many features, such as automatic JSON transformation, interception of requests and responses, and support for the Promise API. Fetch API is a native web API that is also available in React Native, and it provides a simple way to make network requests using promises.

To use Axios in React Native, you need to install it as a dependency in your project using the command npm install axios. Then, you can import it in your component file and create an instance of Axios with the base URL of your API. For example:

import axios from 'axios';

const api = axios.create({
  baseURL: 'https://example.com/api',
});

To use Fetch API in React Native, you don’t need to install anything, as it is already built-in. You can use the global fetch function to make requests to your API. For example:

const api = 'https://example.com/api';

Both Axios and Fetch API support the common HTTP methods, such as GET, POST, PUT, and DELETE. To make a GET request to fetch data from an API endpoint, you can use the following syntax:

// Using Axios
api.get('/users')
  .then(response => {
    // Handle the response data
  })
  .catch(error => {
    // Handle the error
  });

// Using Fetch API
fetch(api + '/users')
  .then(response => response.json())
  .then(data => {
    // Handle the data
  })
  .catch(error => {
    // Handle the error
  });

To make a POST request to send data to an API endpoint, you can use the following syntax:

// Using Axios
api.post('/users', {
  name: 'John',
  email: 'john@example.com',
})
  .then(response => {
    // Handle the response data
  })
  .catch(error => {
    // Handle the error
  });

// Using Fetch API
fetch(api + '/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    name: 'John',
    email: 'john@example.com',
  }),
})
  .then(response => response.json())
  .then(data => {
    // Handle the data
  })
  .catch(error => {
    // Handle the error
  });

To make a PUT request to update data on an API endpoint, you can use the following syntax:

// Using Axios
api.put('/users/1', {
  name: 'Jane',
  email: 'jane@example.com',
})
  .then(response => {
    // Handle the response data
  })
  .catch(error => {
    // Handle the error
  });

// Using Fetch API
fetch(api + '/users/1', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    name: 'Jane',
    email: 'jane@example.com',
  }),
})
  .then(response => response.json())
  .then(data => {
    // Handle the data
  })
  .catch(error => {
    // Handle the error
  });

To make a DELETE request to remove data from an API endpoint, you can use the following syntax:

// Using Axios
api.delete('/users/1')
  .then(response => {
    // Handle the response data
  })
  .catch(error => {
    // Handle the error
  });

// Using Fetch API
fetch(api + '/users/1', {
  method: 'DELETE',
})
  .then(response => response.json())
  .then(data => {
    // Handle the data
  })
  .catch(error => {
    // Handle the error
  });

To render the data from the API in your app’s UI, you can use the React Native components, such as Text, Image, FlatList, etc. You can also use the useState and useEffect hooks to manage the state and lifecycle of your component. For example, to display a list of users from the API, you can use the following code:

import React, { useState, useEffect } from 'react';
import { View, Text, FlatList, StyleSheet } from 'react-native';
import axios from 'axios';

const api = axios.create({
  baseURL: 'https://example.com/api',
});

const UsersScreen = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    // Fetch users from the API
    setLoading(true);
    api.get('/users')
      .then(response => {
        setUsers(response.data);
        setLoading(false);
      })
      .catch(error => {
        setError(error.message);
        setLoading(false);
      });
  }, []);

  // Render a loading indicator if the data is not ready
  if (loading) {
    return (
      <View style={styles.center}>
        <Text>Loading...</Text>
      </View>
    );
  }

  // Render an error message if there is an error
  if (error) {
    return (
      <View style={styles.center}>
        <Text>{error}</Text>
      </View>
    );
  }

  // Render the list of users
  return (
    <View style={styles.container}>
      <FlatList
        data={users}
        keyExtractor={item => item.id.toString()}
        renderItem={({ item }) => (
          <View style={styles.item}>
            <Text style={styles.name}>{item.name}</Text>
            <Text style={styles.email}>{item.email}</Text>
          </View>
        )}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  center: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  item: {
    padding: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#ccc',
  },
  name: {
    fontSize: 18,
    fontWeight: 'bold',
  },
  email: {
    fontSize: 14,
    color: '#555',
  },
});

export default UsersScreen;

Conclusion 

In this guide, we learned how to consume REST APIs in React Native using either the Fetch API or Axios.

This will help you get started with API consumption in React Native, and from there you will be able to consume data in more complex ways and manipulate your APIs however you choose.

Post a Comment

0 Comments