Skip to content

Instantly share code, notes, and snippets.

@djmccormick
Created June 12, 2017 07:54
Show Gist options
  • Save djmccormick/06ed5bb7d2e1169396d63f82b9bed807 to your computer and use it in GitHub Desktop.
Save djmccormick/06ed5bb7d2e1169396d63f82b9bed807 to your computer and use it in GitHub Desktop.
A base react component supporting Immutable state, smarter shouldComponentUpdate, and related helper methods.
import Immutable from 'immutable';
import { Component } from 'react';
import _ from 'lodash';
import shallowEqual from 'shallowequal';
export default class BaseComponent extends Component {
constructor() {
super(...arguments);
this.state = { data: this.getDefaultState() };
}
shouldComponentUpdate(nextProps, nextState) {
return !shallowEqual(nextProps, this.props) || nextState.data !== this.state.data;
}
getDefaultState() {
return Immutable.Map();
}
updateState(mutator, callback = _.noop) {
return new Promise(resolve => {
this.setState(state => {
return { data: mutator(state.data) };
}, () => {
resolve(this.state.data);
callback(this.state.data);
});
});
}
getState(path, defaultValue) {
const state = this.state.data;
if (!path) {
return state;
}
return _.isArray(path) ? state.getIn(path, defaultValue) : state.get(path, defaultValue);
}
resetState(callback = _.noop) {
return this.updateState(state => this.getDefaultState(), callback);
}
}
@djmccormick
Copy link
Author

Needs Lodash, shallowequal, and Immutable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment