In this section, we will learn how to integrate REST APIs into a React Native application. REST APIs are a common way to interact with backend services, allowing us to fetch, create, update, and delete data. We will cover the following topics:

  1. Understanding REST APIs
  2. Setting Up Axios
  3. Making GET Requests
  4. Making POST Requests
  5. Handling PUT and DELETE Requests
  6. Error Handling
  7. Practical Exercise

  1. Understanding REST APIs

REST (Representational State Transfer) is an architectural style for designing networked applications. It relies on a stateless, client-server, cacheable communications protocol -- the HTTP. RESTful applications use HTTP requests to perform CRUD (Create, Read, Update, Delete) operations.

Key Concepts:

  • Endpoint: A specific URL where an API can be accessed.
  • HTTP Methods: Common methods include GET, POST, PUT, DELETE.
  • Status Codes: Indicate the result of the HTTP request (e.g., 200 for success, 404 for not found).

  1. Setting Up Axios

Axios is a popular HTTP client for making requests. It is promise-based and works in both the browser and Node.js environments.

Installation:

npm install axios

Basic Setup:

import axios from 'axios';

const api = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 1000,
  headers: {'Authorization': 'Bearer YOUR_TOKEN'}
});

  1. Making GET Requests

GET requests are used to retrieve data from a server.

Example:

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

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

  useEffect(() => {
    axios.get('https://api.example.com/data')
      .then(response => {
        setData(response.data);
        setLoading(false);
      })
      .catch(error => {
        console.error(error);
        setLoading(false);
      });
  }, []);

  if (loading) {
    return <ActivityIndicator />;
  }

  return (
    <View>
      <Text>{JSON.stringify(data, null, 2)}</Text>
    </View>
  );
};

export default FetchData;

Explanation:

  • useEffect: Fetches data when the component mounts.
  • axios.get: Makes a GET request to the specified URL.
  • setData: Updates the state with the fetched data.
  • ActivityIndicator: Displays a loading spinner while data is being fetched.

  1. Making POST Requests

POST requests are used to send data to a server.

Example:

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

const PostData = () => {
  const [input, setInput] = useState('');
  const [response, setResponse] = useState(null);

  const handleSubmit = () => {
    axios.post('https://api.example.com/data', { data: input })
      .then(response => {
        setResponse(response.data);
      })
      .catch(error => {
        console.error(error);
      });
  };

  return (
    <View>
      <TextInput
        value={input}
        onChangeText={setInput}
        placeholder="Enter data"
      />
      <Button title="Submit" onPress={handleSubmit} />
      {response && <Text>{JSON.stringify(response, null, 2)}</Text>}
    </View>
  );
};

export default PostData;

Explanation:

  • TextInput: Captures user input.
  • axios.post: Sends a POST request with the input data.
  • handleSubmit: Handles the form submission and updates the state with the server response.

  1. Handling PUT and DELETE Requests

PUT requests are used to update existing data, while DELETE requests are used to remove data.

PUT Example:

axios.put('https://api.example.com/data/1', { data: 'Updated data' })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

DELETE Example:

axios.delete('https://api.example.com/data/1')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

  1. Error Handling

Proper error handling is crucial for a robust application.

Example:

axios.get('https://api.example.com/data')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    if (error.response) {
      // Server responded with a status other than 200 range
      console.error('Error response:', error.response.data);
    } else if (error.request) {
      // Request was made but no response received
      console.error('Error request:', error.request);
    } else {
      // Something else happened
      console.error('Error message:', error.message);
    }
  });

  1. Practical Exercise

Task:

Create a simple React Native app that fetches a list of users from a public API and displays them in a list.

Steps:

  1. Set up a new React Native project.
  2. Install Axios.
  3. Create a component that fetches data from https://jsonplaceholder.typicode.com/users.
  4. Display the list of users in a FlatList.

Solution:

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

const UserList = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);

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

  if (loading) {
    return <ActivityIndicator />;
  }

  return (
    <View>
      <FlatList
        data={users}
        keyExtractor={item => item.id.toString()}
        renderItem={({ item }) => (
          <View>
            <Text>{item.name}</Text>
            <Text>{item.email}</Text>
          </View>
        )}
      />
    </View>
  );
};

export default UserList;

Explanation:

  • FlatList: Efficiently renders a list of users.
  • keyExtractor: Ensures each list item has a unique key.
  • renderItem: Defines how each user item should be displayed.

Conclusion

In this section, we covered the basics of integrating REST APIs into a React Native application using Axios. We learned how to make GET, POST, PUT, and DELETE requests, handle errors, and implemented a practical exercise to reinforce these concepts. Understanding how to interact with REST APIs is essential for building dynamic and data-driven applications. In the next module, we will explore more advanced concepts and techniques to further enhance our React Native skills.

© Copyright 2024. All rights reserved