Updating Data

Sekarang kita coba untuk melakukan edit

App.js

import React, {Component} from "react";
import axios from 'axios';
import './App.css';

const ApiEndpoint = "https://jsonplaceholder.typicode.com/posts";

class App extends Component {
  state ={
    posts: []
  };

  async componentDidMount() {
    // pending > resolved (success) OR rejected (failure)
    const { data : posts } = await axios.get(ApiEndpoint);
    this.setState({ posts });
    // console.log(posts)
  }

  handleAdd = async () => {
    const obj = { title: "a", body: "b" };
    const { data: post } = await axios.post(ApiEndpoint, obj);
    // console.log(post)
    const posts = [post, ...this.state.posts]
    this.setState({ posts })
  }

  handleUpdate = async post => {
    post.title = "UPDATED";
    const { data } = await axios.put(ApiEndpoint + '/' + post.id, post);

    const posts = [...this.state.posts];
    const index = posts.indexOf(post);
    posts[index] = {...post};
    this.setState({ posts })
    console.log(data)
  }

  handleDelete = post => {
    console.log("Delete", post);
  }

  render() {
    return (
      <>
        <button className="btn btn-primary" onClick={this.handleAdd}>
          Add
        </button>
        <table className="table">
          <thead>
            <tr>
              <th>Title</th>
              <th>Update</th>
              <th>Delete</th>
            </tr>
          </thead>
          <tbody>
            {this.state.posts.map(post => (
              <tr key={post.id}>
                <td>{post.title}</td>
                <td>
                  <button
                    className="btn btn-info btn-sm"
                    onClick={() => this.handleUpdate(post)}
                  >
                    Update
                  </button>
                </td>
                <td>
                  <button
                    className="btn btn-danger btn-sm"
                    onClick={() => this.handleDelete(post)}
                  >
                    Delete
                  </button>
                </td>
            </tr>
            ))}
          </tbody>
        </table>
      </>
    );
  }
}

export default App;

Last updated

Was this helpful?