Last active
April 8, 2016 19:27
-
-
Save nfcampos/512076429479c7c9b7243be0b33ec924 to your computer and use it in GitHub Desktop.
withPromisedProps
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
import withPromisedProps from './withPromisedProps' | |
import {dsvFormat} from 'd3-dsv' | |
const CsvTable = ({table}) => ( | |
{table.fulfilled && | |
<Table | |
headings={table.value.columns} | |
data={table.value.slice(0, 10)} />} | |
) | |
export default withPromisedProps({ | |
table: { | |
dependentProps: ['file', 'delim'], | |
then: ({file, delim}) => promisedFileReader(file) | |
.readAsText() | |
.then(str => dsvFormat(delim).parse(str)) | |
} | |
})(CsvTable) |
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
import React from 'react' | |
import {PromiseState} from 'react-refetch' | |
import createHelper from 'recompose/createHelper' | |
import createElement from 'recompose/createElement' | |
import {shallowEqual} from '../utils/' | |
const withPromisedProps = (mappings, options) => BaseComponent => { | |
const promisedProps = Object.entries(mappings) | |
return class extends React.Component { | |
componentWillMount() { | |
for (const [prop, {then}] of promisedProps) { | |
this.mapPromisedProp(prop, then(this.props)) | |
} | |
} | |
componentWillReceiveProps(nextProps) { | |
for (const [prop, {dependentProps: deps, then}] of promisedProps) { | |
if ( !shallowEqual(this.props, nextProps, deps) ) { | |
this.mapPromisedProp(prop, then(nextProps)) | |
} | |
} | |
} | |
mapPromisedProp(prop, promise) { | |
this.setState({ [prop]: PromiseState.create() }) | |
promise | |
.then(value => this.setState({ [prop]: PromiseState.resolve(value) })) | |
.catch(reason => this.setState({ [prop]: PromiseState.reject(reason) })) | |
} | |
render() { | |
const props = options.withRef | |
? {...this.props, ...this.state, ref: ref => this.wrappedInstance = ref} | |
: {...this.props, ...this.state} | |
return createElement(BaseComponent, props) | |
} | |
} | |
} | |
export default createHelper(withPromisedProps, 'withPromisedProps') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment