-
Notifications
You must be signed in to change notification settings - Fork 0
React Async `fetch()`
sergio edited this page Jan 28, 2021
·
2 revisions
Async functions are commonly called after the component mounted. The response is then stored in State.
import React, { Component } from 'react'
class App extends Component {
state = {
peopleInSpace: []
}
render() {
return (
<div>
{this.state.peopleInSpace.map(person => person.name)}
</div>
)
}
componentDidMount() {
fetch('http://api.open-notify.org/astros.json')
.then(response => response.json())
.then(data => {
this.setState({
peopleInSpace: data.people
})
})
}
}
export default Appoff course fetch() requests are also commonly launched from event listeners
handleClick = event => {
fetch('your API url')
.then(res => res.json())
.then(json => this.setState({data: json}))
}
render() {
return (
<button onClick={this.handleClick}>Click to Fetch!</button>
)
}More complicated example would be the infinite scroll of sites like Instagram. An event listener tied to changes in the scroll position of a page could fire off a handleScroll method that requests data before a user reaches the bottom of a page.
If we were building a form to submit to a server, we can structure state to work nicely with what the server is expecting in a POST request.
When setting up the fetch request, we can just pass the entire state within the body, as there are no other values.
state = {
username: "",
password: ""
}
//since the id values are the same as the keys in state, we can write an abstract setState here
handleChange = event => {
this.setState({
[event.target.id]: event.target.value
})
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="text" id="username" value={this.state.username} onChange={this.handleChange}/>
<input type="text" id="password" value={this.state.password} onChange={this.handleChange}/>
</form>
)
}
handleSubmit = event => {
event.preventDefault()
fetch('the server URL', {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(this.state)
})
}
- Mounting -
static getDerivedStateFromProps(props, state)- Mounting -
componentDidMount()- Updating -
static getDerivedStateFromProps(props, state)- Updating -
shouldComponentUpdate(nextProps, nextState)- Updating -
render()- Updating -
getSnapshotBeforeUpdate(prevProps, prevState)- Updating -
componentDidUpdate(prevProps, prevState, snapshot)- Unmounting -
componentWillUnmount()- Element Ref