Skip to content

Instantly share code, notes, and snippets.

@hunterc hunterc/Fetch.js
Created Oct 5, 2017

Embed
What would you like to do?
<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
You can’t perform that action at this time.