Skip to content

Instantly share code, notes, and snippets.

@suhaotian
Created December 19, 2016 15:44
Show Gist options
  • Select an option

  • Save suhaotian/5ba34a78aecbc71db4e6413dd70a858e to your computer and use it in GitHub Desktop.

Select an option

Save suhaotian/5ba34a78aecbc71db4e6413dd70a858e to your computer and use it in GitHub Desktop.
React Fetch Component
import React, { Component, PropTypes } from 'react'
//import styles from './style.css'
class ComponentName extends Component {
// static defaultProps = {}
static propTypes = {
promises: PropTypes.array.isRequired,
children: PropTypes.func.isRequired,
}
state = {
error: null,
fetching: true,
data: null,
}
// shouldComponentUpdate(nextProps, nextState) {}
componentDidMount() {
const { promises } = this.props
Promise.all(promises)
.then(result => {
if (this.willUnmout) return
this.setState({
fetching: false,
data: result,
})
})
.catch(e => {
if (this.willUnmout) return
this.setState({fetching: false, error: e})
})
}
componentWillUnmount() {
this.willUnmount = true
}
render() {
const {error, fetching, data,} = this.state
if (fetching) return <div>loading</div>
else if (data) return this.props.children(data)
else return <div>{error.toString()}</div>
}
}
export default ComponentName
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment