Skip to content

Commit

Permalink
Merge branch 'master' into valid_elem
Browse files Browse the repository at this point in the history
  • Loading branch information
developit committed Aug 13, 2019
2 parents 1d73adc + 6f9a9cf commit 6c8adcc
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
14 changes: 13 additions & 1 deletion debug/src/debug.js
@@ -1,6 +1,6 @@
import { checkPropTypes } from './check-props';
import { getDisplayName } from './devtools/custom';
import { options } from 'preact';
import { options, Component } from 'preact';
import { ELEMENT_NODE, DOCUMENT_NODE, DOCUMENT_FRAGMENT_NODE } from './constants';

function getClosestDomNodeParent(parent) {
Expand Down Expand Up @@ -260,6 +260,18 @@ export function initDebug() {
};
}

const setState = Component.prototype.setState;
Component.prototype.setState = function(update, callback) {
if (this._vnode==null) {
console.warn(
`Calling "this.setState" inside the constructor of a component is a ` +
`no-op and might be a bug in your application. Instead, set ` +
`"this.state = {}" directly.`
);
}
return setState.call(this, update, callback);
};

/**
* Serialize a vnode tree to a string
* @param {import('./internal').VNode} vnode
Expand Down
16 changes: 16 additions & 0 deletions debug/test/browser/debug.test.js
Expand Up @@ -205,6 +205,22 @@ describe('debug', () => {
expect(fn).to.throw(/createElement/);
});

it('should warn when calling setState inside the constructor', () => {
class Foo extends Component {
constructor(props) {
super(props);
this.setState({ foo: true });
}
render() {
return <div>foo</div>;
}
}

render(<Foo />, scratch);
expect(console.warn).to.be.calledOnce;
expect(console.warn.args[0]).to.match(/no-op/);
});

it('should warn for useless useMemo calls', () => {
const App = () => {
const [people] = useState([40, 20, 60, 80]);
Expand Down

0 comments on commit 6c8adcc

Please sign in to comment.