Created
August 30, 2019 06:25
-
-
Save behnood-eghbali/274e3da414c924c2c09b4eb083e9f776 to your computer and use it in GitHub Desktop.
Implementing HTTP methods (GET & POST) with json-server and React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react'; | |
import './App.css'; | |
export default class Get extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
error: null, | |
isLoaded: false, | |
items: [] | |
} | |
} | |
componentDidMount() { | |
let url = 'http://localhost:3001/items'; | |
fetch(url) | |
.then(res => res.json()) | |
.then(data => { | |
let items = data.map((item, index) => { | |
return ( | |
<div key={index}> | |
<h2>{item.id}</h2> | |
<h2>{item.name}</h2> | |
<h2>{item.price}</h2> | |
</div> | |
) | |
}) | |
this.setState({items: items}); | |
}) | |
} | |
render() { | |
return ( | |
<div className="MyApp"> | |
<header className="MyApp-header"> | |
<h1>hello world!</h1> | |
</header> | |
{this.state.items} | |
</div> | |
); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react'; | |
import './App.css'; | |
export default class Post extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
error: null, | |
isLoaded: false, | |
item: '', | |
items: [] | |
}; | |
this.handleChange = this.handleChange.bind(this); | |
this.handleSubmit = this.handleSubmit.bind(this); | |
} | |
handleChange(event) { | |
this.setState({item: event.target.value}); | |
} | |
handleSubmit(event) { | |
event.preventDefault(); | |
/* this.setState({ | |
item: '', | |
items: [...this.state.items, this.state.item] | |
}); */ | |
let url = 'http://localhost:3001/items'; | |
fetch(url, { | |
method: 'POST', | |
body: { | |
id: this.state.id, | |
item: this.state.item | |
} | |
}) | |
.then(res => res.json()) | |
.then(data => { | |
this.setState({ | |
isLoaded: true, | |
items: [...this.state.items, this.state.item] | |
}) | |
}); | |
} | |
/* handleData() { | |
} | |
componentDidMount() { | |
} */ | |
render() { | |
return ( | |
<div className="MyApp"> | |
<header className="MyApp-header"> | |
<h1>hello world!</h1> | |
</header> | |
<form onSubmit={this.handleSubmit}> | |
<input type="text" value={this.state.item} onChange={this.handleChange} /> | |
</form> | |
{this.state.items.map((item, i) => | |
<p key={i}>{item}</p> | |
)} | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment