react-native-web
Version:
React Native for Web
77 lines (75 loc) • 2.33 kB
JavaScript
;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
var React = _interopRequireWildcard(require("react"));
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
/**
* `setState` is called asynchronously, and should not rely on the value of
* `this.props` or `this.state`:
* https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous
*
* SafePureComponent adds runtime enforcement, to catch cases where these
* variables are read in a state updater function, instead of the ones passed
* in.
*/
class StateSafePureComponent extends React.PureComponent {
constructor(props) {
super(props);
this._inAsyncStateUpdate = false;
this._installSetStateHooks();
}
setState(partialState, callback) {
if (typeof partialState === 'function') {
super.setState((state, props) => {
this._inAsyncStateUpdate = true;
var ret;
try {
ret = partialState(state, props);
} catch (err) {
throw err;
} finally {
this._inAsyncStateUpdate = false;
}
return ret;
}, callback);
} else {
super.setState(partialState, callback);
}
}
_installSetStateHooks() {
var that = this;
var props = this.props,
state = this.state;
Object.defineProperty(this, 'props', {
get() {
(0, _invariant.default)(!that._inAsyncStateUpdate, '"this.props" should not be accessed during state updates');
return props;
},
set(newProps) {
props = newProps;
}
});
Object.defineProperty(this, 'state', {
get() {
(0, _invariant.default)(!that._inAsyncStateUpdate, '"this.state" should not be acceessed during state updates');
return state;
},
set(newState) {
state = newState;
}
});
}
}
exports.default = StateSafePureComponent;
module.exports = exports.default;