Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@istarkov
Created September 3, 2017 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save istarkov/77d69dddbabf7200cd4203c75e2f0cf7 to your computer and use it in GitHub Desktop.
Save istarkov/77d69dddbabf7200cd4203c75e2f0cf7 to your computer and use it in GitHub Desktop.
/* @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