API Integration
In this tutorial, we will explore how to integrate external APIs into your React application. We will cover the usage of both the native fetch function and the popular library axios.
Preparing API Endpoint
For this tutorial, we will use the JSONPlaceholder API (https://jsonplaceholder.typicode.com) as an example. It provides a simple RESTful API for fetching, creating, updating, and deleting data.
Fetching Data with fetch
fetch is a native function in modern browsers that allows you to make network requests. Let's create a simple component to fetch and display a list of posts:
import React, { useState, useEffect } from 'react';
function PostsList() {
  const [posts, setPosts] = useState([]);
  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then(response => response.json())
      .then(data => setPosts(data));
  }, []);
  return (
    <div>
      <h1>Posts List</h1>
      <ul>
        {posts.map(post => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </div>
  );
}
export default PostsList;
Here, we use the useState and useEffect hooks to fetch and store the data. The fetch function returns a Promise that resolves to the Response object. We then convert the response to JSON and store it in the posts state.
Fetching Data with axios
axios is a popular third-party library for making HTTP requests in JavaScript. It has a more user-friendly API and additional features compared to fetch. First, you need to install it:
npm install axios
Now, let's refactor the PostsList component to use axios:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function PostsList() {
  const [posts, setPosts] = useState([]);
  useEffect(() => {
    axios.get('https://jsonplaceholder.typicode.com/posts').then(response => setPosts(response.data));
  }, []);
  return (
    <div>
      <h1>Posts List</h1>
      <ul>
        {posts.map(post => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </div>
  );
}
export default PostsList;
The main difference here is the usage of axios.get() instead of fetch. axios automatically converts the response to JSON, so there is no need to call response.json().
Conclusion
That's it! You now have a basic understanding of how to integrate external APIs into your React application using both fetch and axios. Remember to handle errors and edge cases according to your specific requirements.