google-map-react/develop/utils/withStateSelector.js
Joe Maffei f5bb716291 Add UNSAFE_ prefix to deprecated lifecycle methods (#778)
* add UNSAFE_ prefix to deprecated lifecycle methods

* add missing line break
2019-09-20 19:41:26 +02:00

45 lines
1.2 KiB
JavaScript

import { Component } from 'react';
import createHelper from './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
);
UNSAFE_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');