Skip to content

Instantly share code, notes, and snippets.

@newswim
Created September 27, 2016 16:52
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save newswim/5bbd009c9fcc9baa4cb439aa1db87352 to your computer and use it in GitHub Desktop.
Save newswim/5bbd009c9fcc9baa4cb439aa1db87352 to your computer and use it in GitHub Desktop.
Fetching data with React's constructor
// I did not write this.
var url = "https://jsonplaceholder.typicode.com/albums"
// Auto unwrap the response as we want the data not the full headers for this simple example
const stringifyResponse = response => {
if (response.status >= 400) throw new Error(response)
return response.headers.get("Content-Type").includes("application/json") ? response.json() : response.text()
}
// use Fetch to pull some test data
// This would be in it's own util module
var get = (url, data) => (
fetch(url, {
body: data
})
.then(response => stringifyResponse(response))
)
// Component to show simple Album
var Album = (props) => {
return <div>
<label>title</label> {props.title}
</div>
}
// Main component, gets the data and renders an array of Albums
class Hello extends React.Component {
constructor() {
super()
// Make call to API to get Album data
get(url, null).then((results) => {
// Loop over results and convert JSON data to Album Components
var albums = results.map((album) => {
return <Album key={album.title} {...album}/>
})
// Store the Components into state so that Render will call and update DOM
this.setState( {albums})
})
// Need something otherwise NPE will occur
this.state = { 'albums': "Please Wait"}
}
render() {
return <div>
Hello {this.props.name}
{this.state.albums}
</div>
}
}
ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment