Created
March 28, 2017 10:42
-
-
Save kwijibo/5a527c7fb265cbe948f81a1243ecb126 to your computer and use it in GitHub Desktop.
React and async data
This file contains hidden or 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 from 'react' | |
import ReactDOM from 'react-dom' | |
class App extends Component { | |
getInitialState(){ | |
return {data: ''} | |
} | |
componentWillMount(){ | |
this.props.dataPromise.then(data => this.setState({data})) | |
} | |
render(){ | |
return (<p>{this.state.data}</p>) | |
} | |
} | |
const dataPromise = Promise.resolve("Hello World") | |
ReactDOM.render(<App dataPromise={dataPromise}/>, document.body) |
This file contains hidden or 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 from 'react' | |
import ReactDOM from 'react-dom' | |
const makeHTML = data => (<p>{data}</p>) | |
const dataPromise = Promise.resolve("Hello World") | |
dataPromise.then(data => | |
ReactDOM.render(makeHTML(data), document.body) | |
) |
This file contains hidden or 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 from 'react' | |
import ReactDOM from 'react-dom' | |
const States = { | |
LOADING: 1, | |
FETCHED: 2, | |
FAILED: 3 | |
} | |
class DataFetch extends Component { | |
getInitialState(){ | |
return {status: States.LOADING, data: null, err: null } | |
} | |
componentWillMount(){ | |
this.props.dataPromise.then(data => { | |
this.setState({data, status: States.FETCHED}) | |
}).catch(err => { | |
this.setState({err, status: States.FAILED}) | |
}) | |
} | |
render(){ | |
const {renderer, failureMessage} = this.props | |
const {status, data, err} = this.state | |
switch(status){ | |
case States.LOADING: | |
return (<img src="spinner.gif"/>) | |
case States.FAILED: | |
return (<p className="text-error">{failureMessage}: {err}</p>) | |
case States.FETCHED: | |
return (<div>{renderer(data)}</div>) | |
} | |
} | |
} | |
const dataPromise = Promise.resolve("Hello World") | |
const showData = data => (<p>{data}</p>) | |
ReactDOM.render( | |
<DataFetch dataPromise={dataPromise} renderer={showData} failureMessage="Sorry couldn't fetch message"/>, | |
document.body | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment