Created
March 17, 2018 12:18
-
-
Save wayanjimmy/a5d4c1a57a1f9e27a9a5ce1863950918 to your computer and use it in GitHub Desktop.
Fetch as a component
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 PropTypes from 'prop-types' | |
import { request } from '../api' | |
class Fetch extends React.Component { | |
static propTypes = { | |
url: PropTypes.string.isRequired, | |
render: PropTypes.func.isRequired, | |
loader: PropTypes.element, | |
} | |
static defaultProps = { | |
url: '', | |
loader: null, | |
render: () => {}, | |
} | |
state = { | |
isLoading: true, | |
response: null, | |
} | |
fetch = async () => { | |
const response = await request().get(this.props.url) | |
this.setState({ isLoading: false, response }) | |
} | |
componentDidMount() { | |
this.setState({ isLoading: true }, this.fetch) | |
} | |
render() { | |
if (this.state.isLoading) { | |
return this.props.loader | |
} | |
return this.props.render({ | |
data: this.state.response.data, | |
}) | |
} | |
} | |
export default Fetch |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment