Getting Data

Kita akan get data dari api

App.js

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

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

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

  handleAdd = () => {
    console.log("Add");
  }

  handleUpdate = post => {
    console.log("Update", post);
  }

  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?