Skip to content

Instantly share code, notes, and snippets.

@ndugger
Last active March 31, 2017 19:34
Show Gist options
  • Save ndugger/3f707b0940b4d64e2dae9caa66d02d57 to your computer and use it in GitHub Desktop.
Save ndugger/3f707b0940b4d64e2dae9caa66d02d57 to your computer and use it in GitHub Desktop.
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