#react #axios #map
import React, { Component } from "react";
const axios = require("axios");
class App extends Component {
constructor() {
super();
this.state = {
persons: [],
posts: [],
name: '',
id: ''
};
this.onButtonClick = this.onButtonClick.bind(this)
this.onInput1Change = this.onInput1Change.bind(this)
this.onForm1Submit = this.onForm1Submit.bind(this)
this.onInput2Change = this.onInput2Change.bind(this)
this.onForm2Submit = this.onForm2Submit.bind(this)
}
componentDidMount() {
axios.get('https://jsonplaceholder.typicode.com/users')
.then(res => {
console.log(res);
this.setState({ persons: res.data })
}
)
.catch(error => {
console.log(error)
})
}
onButtonClick(event) {
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(
resButton => {
console.log(resButton);
this.setState({ posts: resButton.data })
}
)
.catch(error => {
console.log(error)
})
}
onInput1Change(event) {
console.log(this.state.name);
this.setState({name: event.target.value});
}
onForm1Submit = (event) => {
event.preventDefault();
const user = {
name: this.state.name
}
axios.post('https://jsonplaceholder.typicode.com/users',{user})
.then(res=>{
console.log(res);
console.log("submitted ! ==> "+res.data);
})
.catch(error => {
console.log(error)
})
}
onInput2Change(event) {
this.setState({name: event.target.value})
console.log(this.state.name);
}
onInput2Change(event) {
this.setState({id: event.target.value})
console.log(this.state.id);
}
onForm2Submit(event) {
event.preventDefault();
const user = {
name: this.state.name
}
axios.delete('https://jsonplaceholder.typicode.com/users/${this.state.id}',{user})
.then(res=>{
console.log(res);
console.log("deleted user ==> "+user)
})
.catch(error => {
console.log(error)
})
}
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 Posts</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>
<form onSubmit={this.onForm1Submit} >
<label>
register new user
<input placeholder="input new user" id="input1" onChange={this.onInput1Change} value={this.state.name}></input>
</label>
<button id="button2" onClick={this.onForm1Submit} >register</button>
</form>
</div>
<div>
<form onSubmit={this.onForm2Submit} >
<label>
delete users :
</label>
<input placeholder="delete users" id="input2" onChange={this.onInput2Change} >
</input>
<button onClick={this.onForm2Submit} >delete user !</button>
</form>
</div>
</div>
);
}
}
export default App;