google-map-react/develop/utils/withStateSelector.js
Ivan Starkov 07368e23ad Move 2 yarn, add prettier, update linters (#360)
* Move 2 yarn, add prettier, update linters

* Fix linting error
2017-04-11 00:47:54 +03:00

45 lines
1.2 KiB
JavaScript

import { Component } from 'react';
import createHelper from 'recompose/createHelper';
import createEagerFactory from './createEagerFactory';
const withStateSelector = (stateName, stateUpdaterName, selectorFactory) =>
BaseComponent => {
const factory = createEagerFactory(BaseComponent);
return class extends Component {
selector = selectorFactory();
state = {
stateValue: this.selector(this.props),
};
updateStateValue = (updateFn, callback) =>
this.setState(
({ stateValue }) => ({
stateValue: typeof updateFn === 'function'
? updateFn(stateValue)
: updateFn,
}),
callback
);
componentWillReceiveProps(nextProps) {
// reselect memoize result
const nextStateValue = this.selector(nextProps);
if (nextStateValue !== this.state.stateValue) {
this.setState({
stateValue: nextStateValue,
});
}
}
render() {
return factory({
...this.props,
[stateName]: this.state.stateValue,
[stateUpdaterName]: this.updateStateValue,
});
}
};
};
export default createHelper(withStateSelector, 'withStateSelector');