Everything you need as a full stack 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)
Fullstackist aims to provide immersive and explanatory content for full stack developers Fullstackist aims to provide immersive and explanatory content for full stack developers
Backend Developer 103 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

Recent Posts

Web development learning resources and communities for beginners...

TL;DR As a beginner in web development, navigating the vast expanse of online resources can be daunting but with the right resources and communities by your side, you'll be well-equipped to tackle any challenge that comes your way. Unlocking the World of Web Development: Essential Learning Resources and Communities for Beginners As a beginner in web development, navigating the vast expanse of online resources can be daunting. With so many tutorials, courses, and communities vying for attention, it's easy to get lost in the sea of information. But fear not! In this article, we'll guide you through the most valuable learning resources and communities that will help you kickstart your web development journey.

Read more

Understanding component-based architecture for UI development...

Component-based architecture breaks down complex user interfaces into smaller, reusable components, improving modularity, reusability, maintenance, and collaboration in UI development. It allows developers to build, maintain, and update large-scale applications more efficiently by creating independent units that can be used across multiple pages or even applications.

Read more

What is a Single Page Application (SPA) vs a multi-page site?...

Single Page Applications (SPAs) load a single HTML file initially, handling navigation and interactions dynamically with JavaScript, while Multi-Page Sites (MPS) load multiple pages in sequence from the server. SPAs are often preferred for complex applications requiring dynamic updates and real-time data exchange, but MPS may be suitable for simple websites with minimal user interactions.

Read more