Last active
March 31, 2017 19:34
-
-
Save ndugger/3f707b0940b4d64e2dae9caa66d02d57 to your computer and use it in GitHub Desktop.
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 * as Util from '../../util'; | |
import Spinner from '../spinner'; | |
export default class DataLoader extends Component { | |
static defaultProps = { | |
cache: 0, | |
options: { }, | |
placeholder: null | |
} | |
state = { | |
data: null | |
} | |
async componentDidMount () { | |
const { url, options, cache } = this.props; | |
const response = await Util.fetch(url, options, cache); | |
const data = await response.json(); | |
this.setState({ data }); | |
} | |
render () { | |
const { data } = this.state; | |
const { children, placeholder } = this.props; | |
if (!data && !placeholder) { | |
return <Spinner/>; | |
} | |
if (!data && placeholder) { | |
return placeholder; | |
} | |
const elements = children(data); | |
return Array.isArray(elements) | |
? <div>{ elements }</div> | |
: elements; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment