Created
October 5, 2017 02:56
-
-
Save hunterc/63ee0f6b3559b4880b669186adee6ef4 to your computer and use it in GitHub Desktop.
<Fetch> 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
// @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