Created
June 12, 2017 07:54
-
-
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.
This file contains hidden or 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 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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Needs Lodash, shallowequal, and Immutable.