Skip to content

Instantly share code, notes, and snippets.

@hunterc
Created October 5, 2017 02:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hunterc/63ee0f6b3559b4880b669186adee6ef4 to your computer and use it in GitHub Desktop.
Save hunterc/63ee0f6b3559b4880b669186adee6ef4 to your computer and use it in GitHub Desktop.
<Fetch> component
// @flow
import type { Element } from "react"
import React from "react"
import invariant from "invariant"
type State = {
data: Object | null,
error: Error | null,
fetching: boolean
}
type Props = {
children: (state: State) => Element<*>,
resolve: <T>() => Promise<T>
}
export default class Fetch extends React.Component<Props, State> {
state = {
fetching: true,
error: null,
data: null
}
async fetch(resolve: <T>() => Promise<T>) {
try {
const data = await resolve()
this.setState({ fetching: false, error: null, data })
} catch (error) {
this.setState({ fetching: false, error })
}
}
componentDidMount() {
const { resolve } = this.props
invariant(resolve, '<Fetch requires a "resolve" prop')
if (resolve) {
this.fetch(resolve)
}
}
render() {
return this.props.children(this.state)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment