Skip to content

Instantly share code, notes, and snippets.

@elierotenberg
Last active April 12, 2016 13:22
Show Gist options
  • Save elierotenberg/c79ba664be049d18b403f7085626629d to your computer and use it in GitHub Desktop.
Save elierotenberg/c79ba664be049d18b403f7085626629d to your computer and use it in GitHub Desktop.
@stores({
...
})
@debouncePropsUpdate({
x: 1000,
})
@throttlePropsUpdate({
y: 1000,
})
class MyComponent extends React.Component {
...
}
function debouncePropsUpdate(propsConfig) {
return (Component) =>
@pure
class DebouncedComponent extends React.Component {
constructor(...args) {
super(...args);
const [props] = args;
this.state = Object.assign({}, props);
this.stateUpdaters = _.mapValues(propsConfig, (options, key) => {
const spreadableOptions = typeof options === 'number' ? [options] : options;
const updateState = (nextValue) => this.setState({ [key]: nextValue });
const maybeUpdateState = _.debounce(updateState, ...spreadableOptions);
return maybeUpdateState;
});
}
componentWillReceiveProps(nextProps) {
_.each(this.stateUpdaters, (maybeUpdateState, key) => maybeUpdateState(nextProps[key]));
}
render() {
const childProps = Object.assign({}, this.props, this.state);
return <Component {...childProps} />;
}
}
function throttlePropsUpdate(propsConfig) {
return (Component) =>
@pure
class ThrottleComponent extends React.Component {
constructor(...args) {
super(...args);
const [props] = args;
this.state = Object.assign({}, props);
this.stateUpdaters = _.mapValues(propsConfig, (options, key) => {
const spreadableOptions = typeof options === 'number' ? [options] : options;
const updateState = (nextValue) => this.setState({ [key]: nextValue });
const maybeUpdateState = _.throttle(updateState, ...spreadableOptions);
return maybeUpdateState;
});
}
componentWillReceiveProps(nextProps) {
_.each(this.stateUpdaters, (maybeUpdateState, key) => maybeUpdateState(nextProps[key]));
}
render() {
const childProps = Object.assign({}, this.props, this.state);
return <Component {...childProps} />;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment