Skip to content

Instantly share code, notes, and snippets.

@wayanjimmy
Created March 17, 2018 12:18
Show Gist options
  • Save wayanjimmy/a5d4c1a57a1f9e27a9a5ce1863950918 to your computer and use it in GitHub Desktop.
Save wayanjimmy/a5d4c1a57a1f9e27a9a5ce1863950918 to your computer and use it in GitHub Desktop.
Fetch as a component
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