Last active
January 30, 2023 08:43
-
-
Save ryanjduffy/b93be228b00acbba0633ed90071ee00a to your computer and use it in GitHub Desktop.
Log React State Changes
This file contains 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 React from 'react'; | |
const original = React.Component.prototype.setState; | |
const logState = function (type, current, updated) { | |
console.log(type.displayName || type.name || 'Component', 'updating', current, 'with', updated); | |
} | |
const logger = function (partialState, callback) { | |
const type = this._reactInternalInstance._currentElement.type; | |
if (typeof partialState === 'function') { | |
const partialStateCallback = partialState; | |
partialState = function (state, props, context) { | |
const updated = partialStateCallback(state, props, context); | |
logState(type, state, updated); | |
} | |
} else if (partialState) { | |
logState(type, this.state, partialState); | |
} | |
original.call(this, partialState, callback); | |
}; | |
function hijack () { | |
React.Component.prototype.setState = logger; | |
} | |
function restore () { | |
React.Component.prototype.setState = original; | |
} | |
export { | |
hijack, | |
restore | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment