jazst21
1/31/2019 - 8:38 AM

#react #axios #map

#react #axios #map

import React, { Component } from "react";
const axios = require("axios");

class App extends Component {
  constructor() {
    super();
    this.state = {
      persons: [],
      posts: []
    };
    this.onButtonClick = this.onButtonClick.bind(this)
  }
  componentDidMount() {
    axios.get('https://jsonplaceholder.typicode.com/users')
      .then(res => {
        console.log(res);
        this.setState({ persons: res.data })
      }
      )
  }
  onButtonClick(event) {
    axios.get('https://jsonplaceholder.typicode.com/posts')
      .then(
        resButton => {
          console.log(resButton);
          this.setState({ posts: resButton.data })
        }
      )
  }
  render() {
    return (
      <div style={{ textAlign: "center" }}>
        <ul>
          {this.state.persons.map(person => <li key={person.id} >{person.name}</li>)}
        </ul>
        <div>
          <button onClick={this.onButtonClick}  >Click for Manual Fetch</button>
          <ul>
            {this.state.posts.map(
              post => (
                <div key={post.id + post.title} >
                  <li>Post Title : {post.title} </li>
                  <li>Messages : {post.body} </li> <p></p>
                </div>
              )
            )}
          </ul>
        </div>
      </div>
    );
  }
}

export default App;