Everything you need as a full stack web developer

React API Integration with fetch or axios

- Posted in React by

TL;DR Create a new React project using Create React App, install axios, and use it to make GET and POST requests from the API.

React API Integration with fetch or axios: A Beginner's Guide

As a developer, you've probably worked on multiple projects that require fetching data from APIs to display dynamic content to your users. In this article, we'll dive into the world of React API integration using two popular libraries: fetch and axios. We'll cover everything from setting up your project to making successful API calls.

Setting Up Your Project

Before we begin, let's set up a new React project using Create React App:

npx create-react-app react-api-integration

Navigate into the newly created project directory and install the required libraries:

npm install axios

For this example, we'll use axios to make API calls. If you prefer using fetch, simply replace axios with fetch in the code snippets below.

Creating a Component for API Calls

Create a new file called api.js inside your project's src directory:

// src/api.js
import axios from 'axios';

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

export default api;

In this example, we're creating an instance of axios with a base URL set to the JSONPlaceholder API. This will be our go-to API for fetching data throughout this guide.

Making GET Requests

Let's create a simple component that fetches data from the API using axios. Create a new file called Users.js inside your project's src directory:

// src/Users.js
import React, { useState, useEffect } from 'react';
import api from '../api';

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

  useEffect(() => {
    const fetchUsers = async () => {
      try {
        setLoading(true);
        const response = await api.get('/posts');
        setUsers(response.data);
        setLoading(false);
      } catch (err) {
        setError(err.message);
        setLoading(false);
      }
    };
    fetchUsers();
  }, []);

  return (
    <div>
      {loading ? <p>Loading...</p> : null}
      {error ? <p>{error}</p> : null}
      <ul>
        {users.map((user, index) => (
          <li key={index}>{user.title}</li>
        ))}
      </ul>
    </div>
  );
}

export default Users;

In this example, we're using the useState hook to store our API data in a state variable called users. We're also using the useEffect hook to fetch data from the API when the component mounts. The try-catch block is used to handle any errors that might occur during the API call.

Making POST Requests

To make a POST request, we can use the same api.js file and create a new method inside it:

// src/api.js (updated)
import axios from 'axios';

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

export default {
  getPosts() {
    return api.get('/posts');
  },
  createPost(data) {
    return api.post('/posts', data);
  },
};

In the Users.js file, we can now call the createPost method to make a POST request:

// src/Users.js (updated)
import React, { useState } from 'react';
import api from '../api';

function Users() {
  const [postTitle, setPostTitle] = useState('');
  const [postContent, setPostContent] = useState('');

  const handleCreatePost = async () => {
    try {
      const data = { title: postTitle, body: postContent };
      const response = await api.createPost(data);
      console.log(response.data);
    } catch (err) {
      console.error(err.message);
    }
  };

  return (
    <div>
      <input type="text" value={postTitle} onChange={(e) => setPostTitle(e.target.value)} placeholder="Enter post title" />
      <textarea value={postContent} onChange={(e) => setPostContent(e.target.value)} placeholder="Enter post content" />
      <button onClick={handleCreatePost}>Create Post</button>
    </div>
  );
}

export default Users;

In this example, we're using the createPost method to make a POST request with the provided data. We're also logging the response data to the console.

Conclusion

In this article, we've covered the basics of React API integration using axios. We've learned how to set up our project, create a component for API calls, and make both GET and POST requests. With this knowledge, you should be able to fetch data from APIs in your own React applications.

Next Steps:

  • Explore more features of axios and other libraries like fetch
  • Learn about error handling and edge cases
  • Practice making API calls with different types of data (e.g., JSON, XML)
Fullstack.ist offers meaningful insight into a broad range of topics. Fullstack.ist offers meaningful insight into a broad range of topics.
Backend Developer 102 Being a Fullstack Developer 107 CSS 109 Devops and Cloud 70 Flask 108 Frontend Developer 357 Fullstack Testing 99 HTML 171 Intermediate Developer 105 JavaScript 206 Junior Developer 124 Laravel 221 React 110 Senior Lead Developer 124 VCS Version Control Systems 99 Vue.js 108