From c6665e346030f73b7ebb615ce1affe8396b0dab8 Mon Sep 17 00:00:00 2001 From: ngavalas Date: Fri, 14 Jun 2013 16:23:06 -0700 Subject: [PATCH] Adds optional callback to `setState` This commit adds an optional callback as a second argument to `setState`, to be called after `setState` runs. We never guarantee synchronous execution of `setState`, and as per @phunt, we don't want to make that guarantee because we may eventually batch calls to `setState`. @jwalke agrees with him. --- src/core/ReactCompositeComponent.js | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/core/ReactCompositeComponent.js b/src/core/ReactCompositeComponent.js index ac2e57d93c..03f17019f1 100644 --- a/src/core/ReactCompositeComponent.js +++ b/src/core/ReactCompositeComponent.js @@ -525,13 +525,21 @@ var ReactCompositeComponentMixin = { * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * + * There is no guarantee that calls to `setState` will run synchronously, + * as they may eventually be batched together. You can provide an optional + * callback that will be executed when the call to setState is actually + * completed. + * * @param {object} partialState Next partial state to be merged with state. + * @param {?function} callback Called after state is updated. * @final * @protected */ - setState: function(partialState) { + setState: function(partialState, callback) { // Merge with `_pendingState` if it exists, otherwise with existing state. this.replaceState(merge(this._pendingState || this.state, partialState)); + // If `callback` is callable, do it. + typeof callback === 'function' && callback(); }, /**