Skip to content

Instantly share code, notes, and snippets.

@export-mike
Created November 22, 2017 04:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save export-mike/c19817fce496e9e903cf264f57255382 to your computer and use it in GitHub Desktop.
Save export-mike/c19817fce496e9e903cf264f57255382 to your computer and use it in GitHub Desktop.
DataLoadingViaRenderProps
import React from 'react';
import Tile from './Tile';
import {WithRequest} from './withRequest';
import Api from '../Api';
import Loading from './Loading';
const OnBoardingTemplates = () => <Tile
title="Users"
to="/users"
actionLabel="Add New"
>
<WithRequest
fetch={() => Api.templates()}
prop="templates"
LoadingComponent={Loading}
>
{({templates}) => templates.map(template => <div>
{template.name}
</div>)}
</WithRequest>
</Tile>
export default OnBoardingTemplates;
// withRequest.js
export class WithRequest extends React.Component {
static defaultProps = {
fetch: () => {},
prop: 'data',
LoadingComponent: null,
children: () => null
};
componentWillMount() {
this.fetch();
}
fetch = async () => {
try {
this.setState({
...this.state,
loading: true,
errorLoading: false
});
const result = await this.props.fetch();
this.setState({
...this.state,
[this.props.prop]: result
});
} catch (e) {
this.setState({
...this.state,
errorLoading: true,
loading: false
});
}
}
render() {
if (this.props.LoadingComponent) {
return <this.props.LoadingComponent error={this.state.errorLoading} loading={this.state.loading}>
{this.props.children(this.state)}
</this.props.LoadingComponent>
}
return this.props.children(this.state);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment