Last active
July 12, 2018 00:58
-
-
Save raibima/5789c1f9abe6e7ec39cac0fb1ecd1bf9 to your computer and use it in GitHub Desktop.
Simple component setState logger
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
| // Usage | |
| import React from 'react'; | |
| injectLogger(React.Component); | |
| // You can also make it specific to just a component | |
| class App extends React.Component {} | |
| injectLogger(App); | |
| // Injecting logger will add additional boolean param to setState. | |
| // Set this to true to perform setState logging | |
| this.setState( | |
| {}, | |
| undefined, | |
| true // enable logger | |
| ); | |
| // Implementation | |
| function injectLogger(Component) { | |
| const originalSetState = Component.prototype.setState; | |
| Component.prototype.setState = function(...args) { | |
| if (args[2] === true) { | |
| console.group(this.constructor.name); | |
| console.log('prevState', this.state); | |
| let changedState = {}; | |
| if (typeof args[0] === 'function') { | |
| changedState = args[0](this.state); | |
| } else { | |
| changedState = args[0]; | |
| } | |
| console.log('modification', changedState); | |
| } | |
| originalSetState.call(this, args[0], () => { | |
| if (typeof args[1] === 'function') { | |
| args[1](); | |
| } | |
| if (args[2] === true) { | |
| console.log('nextState', this.state); | |
| console.groupEnd(this.constructor.name); | |
| } | |
| }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment