Skip to content

Commit 39506ac

Browse files
Merge pull request #127 from preactjs/fix-setState
Fix exception when invoking setState in cWM
2 parents 29482d4 + 5e7acf3 commit 39506ac

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

src/index.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,9 +104,21 @@ function renderToString(vnode, context, opts, inner, isSvgMode, selectValue) {
104104
c._dirty = c.__d = true;
105105
c.props = props;
106106
if (c.state==null) c.state = {};
107+
108+
if (c._nextState==null && c.__s==null) {
109+
c._nextState = c.__s = c.state;
110+
}
111+
107112
c.context = cctx;
108113
if (nodeName.getDerivedStateFromProps) c.state = assign(assign({}, c.state), nodeName.getDerivedStateFromProps(c.props, c.state));
109114
else if (c.componentWillMount) c.componentWillMount();
115+
116+
// If the user called setState in cWM we need to flush pending,
117+
// state updates. This is the same behaviour in React.
118+
c.state = c._nextState !== c.state
119+
? c._nextState : c.__s!==c.state
120+
? c.__s : c.state;
121+
110122
rendered = c.render(c.props, c.state, c.context);
111123
}
112124

test/render.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -354,6 +354,27 @@ describe('render', () => {
354354
.and.to.have.been.calledBefore(Test.prototype.render);
355355
});
356356

357+
it('should be able to call setState in componentWillMount', () => {
358+
class Test extends Component {
359+
constructor(props) {
360+
super(props);
361+
this.state = { updated: false };
362+
}
363+
componentWillMount() {
364+
this.setState({ updated: true });
365+
}
366+
render() {
367+
return (
368+
<p>
369+
{this.state.updated.toString()}
370+
</p>
371+
);
372+
}
373+
}
374+
375+
expect(render(<Test />)).to.equal('<p>true</p>');
376+
});
377+
357378
it('should invoke getDerivedStateFromProps rather than componentWillMount', () => {
358379
class Test extends Component {
359380
static getDerivedStateFromProps() {}

0 commit comments

Comments
 (0)