Created
November 22, 2017 04:29
-
-
Save export-mike/c19817fce496e9e903cf264f57255382 to your computer and use it in GitHub Desktop.
DataLoadingViaRenderProps
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 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