예제와 함께 React에서 Axios로 DELETE 요청을 보내는 방법

이 튜토리얼에서는 http 삭제 요청을 반응으로 보내는 방법을 배웁니다. 우리는 axios와 React를 사용하여 http 삭제 요청을 보내는 아주 간단한 예제를 제공할 것입니다.

Axios는 npm 패키지이며 애플리케이션에서 http 요청을 제공합니다. 이 예제에서는 "jsonplaceholder" api를 사용하여 axios 패키지를 사용하여 데이터를 삭제합니다.

예제와 함께 React에서 Axios로 DELETE 요청을 보내는 방법

import React from 'react';
  
import axios from 'axios';
  
export default class PostList extends React.Component {
  state = {
    posts: []
  }
  
  componentDidMount() {
    axios.get(`https://jsonplaceholder.typicode.com/posts`)
      .then(res => {
        const posts = res.data;
        this.setState({ posts });
      })
  }
  
  deleteRow(id, e){
    axios.delete(`https://jsonplaceholder.typicode.com/posts/${id}`)
      .then(res => {
        console.log(res);
        console.log(res.data);
  
        const posts = this.state.posts.filter(item => item.id !== id);
        this.setState({ posts });
      })
  
  }
  
  render() {
    return (
      <div>
        <h1>React Axios Delete Request Example</h1>
  
        <table className="table table-bordered">
            <thead>
              <tr>
                  <th>ID</th>
                  <th>Title</th>
                  <th>Body</th>
                  <th>Action</th>
              </tr>
            </thead>
  
            <tbody>
              {this.state.posts.map((post) => (
                <tr>
                  <td>{post.id}</td>
                  <td>{post.title}</td>
                  <td>{post.body}</td>
                  <td>
                    <button className="btn btn-danger" onClick={(e) => this.deleteRow(post.id, e)}>Delete</button>
                  </td>
                </tr>
              ))}
            </tbody>
  
        </table>
      </div>
    )
  }
}

행복한 코딩!!!

3.55 GEEK