Created
September 3, 2017 18:46
-
-
Save istarkov/77d69dddbabf7200cd4203c75e2f0cf7 to your computer and use it in GitHub Desktop.
This file contains 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 * as React from 'react' | |
import { compose, withProps } from 'recompose' | |
import type { HOC } from 'recompose' | |
// Example of very dirty written fetcher enhancer | |
function fetcher<Response: {}, Base: {}>( | |
dest: string, | |
nullRespType: ?Response | |
): HOC<{ ...$Exact<Base>, data?: Response }, Base> { | |
return BaseComponent => | |
class Fetcher extends React.Component<Base, { data?: Response }> { | |
state = { data: undefined } | |
componentDidMount() { | |
fetch(dest) | |
.then(r => r.json()) | |
.then((data: Response) => this.setState({ data })) | |
} | |
render() { | |
return <BaseComponent {...this.props} {...this.state} /> | |
} | |
} | |
} | |
// Test that all is fine | |
// Enhanced Component props type | |
type EnhancedCompProps = { b: number } | |
// response type | |
type FetchResponseType = { hello: string, world: number } | |
// Now you can use it, let's check | |
const enhancer: HOC<*, EnhancedCompProps> = compose( | |
// pass response type via typed null | |
fetcher('http://endpoint.ep', (null: ?FetchResponseType)), | |
// see here fully typed data | |
withProps(({ data }) => ({ | |
data, | |
})) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment