开源日报每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,坚持阅读《开源日报》,保持每日学习的好习惯。
2023年12月29日,开源日报第1058期:
今日推荐开源项目:《awesome-mac》
今日推荐英文原文:《How to Make an API Call with All CRUD Operations in React》


开源项目

今日推荐开源项目:《awesome-mac》传送门:项目链接

推荐理由: 推荐非常好用的 Mac 应用程序、软件以及工具, 通过 Pull Request 或者 issues 给这个仓库推荐优秀好用的Mac应用,文档格式参照 awesome,一起mac 社区变得更加繁荣


英文原文

今日推荐英文原文:How to Make an API Call with All CRUD Operations in React

推荐理由:本文详细介绍了在React中使用Axios来CRUD(创建、读取、更新、删除)操作的方法。通过详细例子演示了如何使用Axios和REST API执行每个操作,同时也有对JSON Placeholder进行API调用的实际示例,并介绍了Axios的设置过程


How to Make an API Call with All CRUD Operations in React

CRUD Operations in React using Axios

Introduction 🌟

Creating, Reading, Updating, and Deleting (CRUD) operations are essential in web development, forming the core of interaction between a user interface and a server. In React applications, especially given their component-based architecture, these operations are integral for creating dynamic user experiences. As each component potentially interacts with data, understanding CRUD operations allows you to manage and display this data effectively.

Throughout this guide, we will explain how to perform each CRUD operation using React and a REST API. For these examples, we’ll be using Axios, a popular and powerful library that simplifies HTTP requests and integrates seamlessly with React’s ecosystem.

Understanding CRUD Operations 🔍

Here’s a quick overview of each CRUD operation and its corresponding HTTP method:

Operation HTTP Method Description
Create POST Adds new data
Read GET Retrieves data
Update PUT/PATCH Modifies existing data
Delete DELETE Removes data

Using JSON Placeholder for API Calls 🌐

For our practical examples, we will utilize JSON Placeholder, a free online REST API that mimics real server responses with fake data. This service is ideal for testing and prototyping, as it provides typical responses you would expect from a real server without the need for setting up a backend. For those interested in exploring or using this tool for their own testing purposes, you can find more information at JSON Placeholder.

Setting Up Axios in Your Project ⚙️

Before diving into CRUD operations, let’s set up Axios in our project. Axios is a popular library for making HTTP requests, preferred over the native fetch API for its automatic handling of JSON data conversion and more user-friendly error handling.

To add Axios to your project, run:

npm install axios

Then, import it into your React component:

import axios from 'axios';

Now your axios set up is ready, let’s dive into the examples

1. GET Operation 📥

The GET operation is used to retrieve data from a server at the specified resource. When you make a GET request, you’re asking the server to send data back to you.

Let’s make a GET request to retrieve a list of posts from JSON Placeholder:

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const Posts = () => {
    const [posts, setPosts] = useState([]);

    useEffect(() => {
        axios.get('https://jsonplaceholder.typicode.com/posts')
            .then(response => {
                setPosts(response.data);
            })
            .catch(error => {
                console.error('Error fetching data:', error);
            });
    }, []);

    return (
        <div>
            <h1>Posts</h1>
            {posts.map(post => (
                <div key={post.id}>
                    <h2>{post.title}</h2>
                    <p>{post.body}</p>
                </div>
            ))}
        </div>
    );
}

export default Posts;

A successful GET request typically returns a status code of 200 OK, along with the requested data, usually in JSON format. In case of failure (e.g., network issues, wrong URL), Axios will catch the error, which can be handled in the .catch block. It's crucial to handle these errors to prevent your application from crashing and to provide feedback to the user.

2. POST Operation (Create) 🆕

The POST method is used to send data to the server to create a new resource. It’s a fundamental part of web development that deals with submitting forms, uploading files, or creating new data entries in a database.

To demonstrate, we’ll create a new post using JSON Placeholder:

import React, { useState } from 'react';
import axios from 'axios';

const CreatePost = () => {
    const [title, setTitle] = useState('');
    const [body, setBody] = useState('');

    const handleSubmit = (e) => {
        e.preventDefault();

        const newPost = { title, body };
        axios.post('https://jsonplaceholder.typicode.com/posts', newPost)
            .then(response => {
                alert(`New Post Created with ID: ${response.data.id}`);
            })
            .catch(error => {
                console.error('Error creating a post:', error);
            });
    };

    return (
        <form onSubmit={handleSubmit}>
            <input type="text" value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Title" />
            <textarea value={body} onChange={(e) => setBody(e.target.value)} placeholder="Body"></textarea>
            <button type="submit">Create Post</button>
        </form>
    );
};

export default CreatePost;

This example demonstrates a typical form in React for submitting data. The useState hooks track form inputs, and the handleSubmit function sends a POST request with the form data.

Understanding the Response

A successful POST request is acknowledged by the server with a 201 Created status code. The response generally contains the data of the newly created resource, including any server-generated fields like an ID. This feedback is crucial for confirming the creation and updating the UI accordingly.

3. PUT/PATCH Operation (Update) 🔄

PUT and PATCH methods are employed for updating existing resources. The distinction lies in their approach: PUT is used for replacing an entire resource, while PATCH is for making partial updates.

To update a post, we’ll create a simple interface with a button. When clicked, it sends a PUT request with a hardcoded payload to update a specific post.

import React from "react";
import axios from "axios";

const UpdatePost = () => {
  const postId = 1; // Assuming we are updating the post with ID 1
  const updatedData = { title: "New Title", body: "Updated body text" };

  const handleUpdate = () => {
    axios
      .put(`https://jsonplaceholder.typicode.com/posts/${postId}`, updatedData)
      .then((response) => {
        console.log("Updated Post:", response.data);
      })
      .catch((error) => {
        console.error("Error updating the post:", error);
      });
  };

  return (
    <div>
      <button onClick={handleUpdate}>Update Post</button>
    </div>
  );
};

export default UpdatePost;

In this example, the handleUpdate function triggers a PUT request with predefined updatedData. This setup simulates updating a post, and upon success, logs the updated post data to the console.

Understanding the Response

When you send a PUT request to update a resource, the server’s response can vary based on the API’s design. Typically, a 200 OK status code is returned, along with the updated resource data. This response confirms that the update was successful and allows you to see the changes made. In some cases, if the update doesn't return any content, you might receive a 204 No Content status. It's important to handle these responses in your application to confirm the update to the user and to update the UI accordingly.

Errors in PUT requests could occur due to various reasons like invalid data sent in the request or trying to update a non-existent resource. These errors are usually indicated by 4xx status codes like 400 Bad Request or 404 Not Found. Proper error handling is crucial for informing users about what went wrong.

4. DELETE Operation 🗑️

For the DELETE operation, we’ll display a list of posts, each with a ‘Delete’ button. Clicking the button will send a DELETE request to remove that specific post.

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const DeletePost = () => {
    const [posts, setPosts] = useState([]);

    useEffect(() => {
        axios.get('https://jsonplaceholder.typicode.com/posts')
            .then(response => {
                setPosts(response.data);
            });
    }, []);

    const handleDelete = (postId) => {
        axios.delete(`https://jsonplaceholder.typicode.com/posts/${postId}`)
            .then(() => {
                setPosts(posts.filter(post => post.id !== postId));
                console.log(`Post with ID ${postId} deleted successfully`);
            })
            .catch(error => {
                console.error('Error deleting the post:', error);
            });
    };

    return (
        <div>
            <h1>Posts</h1>
            {posts.map(post => (
                <div key={post.id}>
                    <h2>{post.title}</h2>
                    <button onClick={() => handleDelete(post.id)}>Delete Post</button>
                </div>
            ))}
        </div>
    );
};

export default DeletePost;

In this DELETE example, each post has a button attached to it. Clicking the button triggers handleDelete, which sends a DELETE request for that specific post. The post list is then updated to reflect the deletion.

Understanding the Response

For DELETE requests, the typical successful response is a 200 OK or 204 No Content status code, often with no return data. This indicates that the resource was successfully deleted. Some APIs might return the deleted resource's data as part of the response, which can be useful for confirming what was deleted or for record-keeping purposes in the application.

In case of failure, such as attempting to delete a resource that doesn’t exist or one that can’t be deleted due to server rules, the server responds with appropriate error status codes like 404 Not Found or 403 Forbidden. Handling these errors is essential to provide clear feedback to the user, ensuring they understand why the operation didn't succeed.

Conclusion 🚀

In this guide, we’ve covered the essential CRUD operations — Create, Read, Update, and Delete — using Axios in React. By walking through each operation with practical examples, we aimed to provide a clear and accessible approach to interacting with APIs in your React applications. Remember, understanding how to make these requests and handle server responses is crucial for building effective and user-friendly web applications.


下载开源日报APP:https://openingsource.org/2579/
加入我们:https://openingsource.org/about/join/
关注我们:https://openingsource.org/about/love/