React Native Axios Get Example

In this article, we’ll explore how to use Axios in a React Native application to perform GET requests. Axios is a popular, promise-based HTTP client that simplifies making requests to external APIs. We’ll go through a practical example of fetching data from a public API and displaying it in a React Native app.

Why Axios for React Native?

Axios is favored in the React Native community due to its ease of use, configurability, and broad compatibility with JavaScript environments. It offers a straightforward way to make HTTP requests and handle responses with promises, making it an excellent choice for React Native developers looking to interact with APIs.

Setting Up Axios

Before we start, ensure Axios is installed in your React Native project. If you haven’t already done so, you can add Axios by running:

npm install axios

or, if you prefer yarn:

yarn add axios

Creating a Component to Fetch and Display Data

For this example, we’ll create a simple component that fetches data from the JSONPlaceholder API, a free fake online REST API that you can use for testing and prototyping.

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

const DataFetcher = () => {
  const [data, setData] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    axios.get('https://jsonplaceholder.typicode.com/posts')
      .then(response => {
        setData(response.data);
        setIsLoading(false);
      })
      .catch(error => {
        console.error(error);
        setIsLoading(false);
      });
  }, []);

  if (isLoading) {
    return <Text>Loading...</Text>;
  }

  return (
    <View style={styles.container}>
      <FlatList
        data={data}
        keyExtractor={({ id }, index) => id.toString()}
        renderItem={({ item }) => (
          <View style={styles.item}>
            <Text style={styles.title}>{item.title}</Text>
            <Text>{item.body}</Text>
          </View>
        )}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 20,
  },
  item: {
    backgroundColor: '#f9c2ff',
    padding: 20,
    marginVertical: 8,
    marginHorizontal: 16,
  },
  title: {
    fontSize: 16,
  },
});

export default DataFetcher;

Understanding the Code

  • useState Hook: We use the useState hook to initialize the data state to an empty array and the isLoading state to true. These states will help us manage the fetched data and the loading state of our component.
  • useEffect Hook: The useEffect hook triggers the Axios GET request when the component mounts. Upon a successful request, we update the data state with the response data and set isLoading to false. If the request fails, we log the error and also set isLoading to false.
  • FlatList Component: We use the FlatList component to render the fetched data as a list. The keyExtractor prop is used to assign a unique key to each list item, and the renderItem prop specifies how each item should be rendered.

Conclusion

This example demonstrates how to use Axios in a React Native application to perform GET requests and display the fetched data. Axios simplifies handling asynchronous operations and managing the response data, making it a valuable tool for React Native developers working with external APIs. Remember, while we used the JSONPlaceholder API for this example, the same principles apply when fetching data from any REST API.

Additional Resources

Leave a Comment