Skip to content

Commit

Permalink
Pass props in setState() callback (#23)
Browse files Browse the repository at this point in the history
  • Loading branch information
ForbesLindesay authored and Vadim Demedes committed Aug 7, 2017
1 parent dae106e commit 9c33272
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/component.js
Expand Up @@ -14,7 +14,7 @@ class Component {

setState(nextState, callback) {
if (typeof nextState === 'function') {
nextState = nextState(this.state);
nextState = nextState(this.state, this.props);
}

this._pendingState = Object.assign({}, this._pendingState || this.state, nextState);
Expand Down
35 changes: 35 additions & 0 deletions test/components.js
Expand Up @@ -395,6 +395,41 @@ test('rerender when state updates', t => {
t.is(renderToString(secondTree), 'Goodbye');
});

test('set state accepts a function', t => {
let component;

class A extends Component {
constructor(props, context) {
super(props, context);

this.state = {
message: 'Hello'
};

component = this;
}

render(props, state) {
return state.message;
}
}

const onUpdate = spy();
const firstTree = build(<A value="message"/>, null, onUpdate);
t.is(renderToString(firstTree), 'Hello');

component.setState((oldState, props) => {
t.is(oldState.message, 'Hello');
t.is(props.value, 'message');
return {message: 'Goodbye'};
});
rerender();
t.true(onUpdate.calledOnce);

const secondTree = build(<A/>, firstTree);
t.is(renderToString(secondTree), 'Goodbye');
});

test('store next state and set it only on rerender', t => {
let component;

Expand Down

0 comments on commit 9c33272

Please sign in to comment.