In this section, we will explore how to use Axios, a popular HTTP client, to make HTTP requests in a React Native application. Axios simplifies the process of making HTTP requests and handling responses, making it a powerful tool for interacting with APIs.

What is Axios?

Axios is a promise-based HTTP client for JavaScript that can be used in both the browser and Node.js environments. It provides a simple and intuitive API for making HTTP requests and handling responses.

Key Features of Axios:

  • Supports the Promise API.
  • Intercept request and response.
  • Transform request and response data.
  • Cancel requests.
  • Automatic JSON data transformation.

Installing Axios

To use Axios in your React Native project, you need to install it via npm or yarn.

npm install axios
# or
yarn add axios

Making a GET Request

Let's start with a simple example of making a GET request to fetch data from an API.

Example: Fetching Data from an API

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

const App = () => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

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

  if (loading) {
    return <ActivityIndicator size="large" color="#0000ff" />;
  }

  if (error) {
    return <Text>Error: {error.message}</Text>;
  }

  return (
    <View style={styles.container}>
      <Text style={styles.title}>{data.title}</Text>
      <Text>{data.body}</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 16,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 8,
  },
});

export default App;

Explanation:

  1. Importing Axios: We import Axios at the top of the file.
  2. State Management: We use useState to manage the state for data, loading, and error.
  3. Fetching Data: Inside useEffect, we make a GET request to fetch data from the API. The response data is stored in the data state, and the loading state is set to false.
  4. Error Handling: If an error occurs, it is caught and stored in the error state.
  5. Conditional Rendering: We conditionally render a loading indicator, an error message, or the fetched data based on the state.

Making a POST Request

Next, let's see how to make a POST request to send data to an API.

Example: Sending Data to an API

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

const App = () => {
  const [title, setTitle] = useState('');
  const [body, setBody] = useState('');
  const [response, setResponse] = useState(null);

  const handleSubmit = () => {
    axios.post('https://jsonplaceholder.typicode.com/posts', {
      title: title,
      body: body,
    })
    .then(response => {
      setResponse(response.data);
    })
    .catch(error => {
      console.error(error);
    });
  };

  return (
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        placeholder="Title"
        value={title}
        onChangeText={setTitle}
      />
      <TextInput
        style={styles.input}
        placeholder="Body"
        value={body}
        onChangeText={setBody}
      />
      <Button title="Submit" onPress={handleSubmit} />
      {response && (
        <View style={styles.responseContainer}>
          <Text style={styles.responseTitle}>Response:</Text>
          <Text>{JSON.stringify(response, null, 2)}</Text>
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    padding: 16,
  },
  input: {
    height: 40,
    borderColor: 'gray',
    borderWidth: 1,
    marginBottom: 12,
    paddingHorizontal: 8,
  },
  responseContainer: {
    marginTop: 16,
  },
  responseTitle: {
    fontSize: 18,
    fontWeight: 'bold',
  },
});

export default App;

Explanation:

  1. State Management: We use useState to manage the state for the title, body, and response.
  2. Handling Form Submission: The handleSubmit function is called when the form is submitted. It makes a POST request to send the title and body to the API.
  3. Updating State: The response data is stored in the response state.
  4. Rendering Response: If there is a response, it is displayed below the form.

Practical Exercise

Exercise: Fetch and Display a List of Users

  1. Create a new React Native component.
  2. Use Axios to fetch a list of users from the API: https://jsonplaceholder.typicode.com/users.
  3. Display the list of users in a FlatList.

Solution:

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

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

  useEffect(() => {
    axios.get('https://jsonplaceholder.typicode.com/users')
      .then(response => {
        setUsers(response.data);
        setLoading(false);
      })
      .catch(error => {
        setError(error);
        setLoading(false);
      });
  }, []);

  if (loading) {
    return <ActivityIndicator size="large" color="#0000ff" />;
  }

  if (error) {
    return <Text>Error: {error.message}</Text>;
  }

  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>{item.email}</Text>
          </View>
        )}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 16,
  },
  item: {
    padding: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#ccc',
  },
  name: {
    fontSize: 18,
    fontWeight: 'bold',
  },
});

export default UsersList;

Explanation:

  1. Fetching Data: We fetch the list of users from the API using Axios.
  2. Displaying Data: We use a FlatList to display the list of users.
  3. Error Handling: We handle errors and display an error message if an error occurs.

Conclusion

In this section, we learned how to use Axios to make HTTP requests in a React Native application. We covered making GET and POST requests, handling responses, and displaying data. Axios simplifies the process of interacting with APIs, making it a valuable tool for any React Native developer.

Next, we will explore how to handle network errors effectively in the following section.

© Copyright 2024. All rights reserved