Make setState return a promise
setState() currently accepts an optional second argument for callback and returns undefined.
This results in a callback hell for a very stateful component. Having it return a promise would make it much more managable.
It is somewhat of a convention in JS world to have API symmetric - if a method accepts a callback, it returns a promise. if it returns a promise, it can accept a callback.
In my case, I have an editable table. If user presses enter, he is moved to the next row (call setState). If the user is on a last row, I'd like to create a new row (call setState) and focus on this new row (call setState). Currently the only way is to achieve this is to have a nested callback hell.
Do you have any ideas about what to do with React.render which also accepts a callback but also returns a value?
There are a few other techniques that can be used. You can have the row's componentDidMount call focus so that it's auto-focused when it is created.
The new style refs are callbacks that get fired when the child is mounted. That can be used to trigger a focus without the need of wrapping it.
You can also use the componentDidUpdate life-cycle hook as a component gets updated to ensure that the focused thing (according to your business logic) always retains focus (e.g. the newest one).
I think that these are probably better alternatives that don't rely on the imperative nature of the source of your state change. E.g. you're tying it to the action that triggered the event. What if you add another state transition to the same state? Isn't it confusing that you can end up in the same state with different side-effects? That's part of the beauty of React, that you can avoid that.
Do you think that one of those patterns could replace your callback?
Even if it isn't... Honestly, the current batching strategy comes with a set of problems right now. I'm hesitant to expand on it's API before we're sure that we're going to keep the current model. I think of it as a temporary escape until we figure out something better.
Does that seem fair?
In my experience, whenever I'm tempted to use setState callback, I can achieve the same by overriding componentDidUpdate (and/or componentDidMount).
I was wondering the same. Thanks @gaearon for the trick it works as expected.
Using componentDidUpdate aside, Promises are a logical way of handling the post setState hook. And promises reflect the current state-of-opinion in the javascript community.
this.setState({
selected: input
}).then(function() {
this.props.didSelect(this.state.selected);
}.bind(this));
Is common React code, and much more readable than a optional callback argument.
Bump.
Why would you use that pattern over this?
this.setState({
selected: input
});
this.props.didSelect(input);
It is in fact probably an anti-pattern to fire an event after updates in that case because it may triggers multiple rendering passes and multiple layout passes which has significantly worse performance implications.
The two code examples are functionally different. Anytime the parent need the child's updated DOM in place, or pending states resolved would be a candidate for the promise.
To come up with a contrived example, lets say the selection state changes the rendered component's width, and the parent needs to calculate a new position to account for this new child width.
Yes these DOM issues can be accounted for with componentDidUpdate, or others. But that's not the point. The point of this issue is to transition the setState interface to something more inline with JS community standards.
The problem with existing JS community practices is that they can often make code difficult to reason about. The nice thing about lifecycle methods is that they make it easy to reason about. There aren't side effects happening in other unexpected places due to some callback. If everything can be handled through lifecycle methods then I would personally advocate removing the setState() callback altogether.
what's a setState callback XD @gaearon
@zzz6519003 It's a callback that can be passed as the second argument to setState() to be called when it is done. See https://facebook.github.io/react/docs/component-api.html#setstate
Do you have any ideas about what to do with
React.renderwhich also accepts a callback but also returns a value?
Two solutions, which aren't mutually exclusive:
(a) the callback gets the component as an argument / the promise returns the component. This will work for all cases where the component value is not needed synchronously.
(b) similarly to how ref={...} takes a function, the caller can supply a 2nd callback that gets called with the component instance, right after ReactDOM.render is done. Though in that case, one would wonder why not simply require that the consumer of ReactDOM.render add a ref={...} prop to the element themselves. In other words:
let el = ReactDOM.render(<Foobar />, div);
doSomethingWith(el);
becomes
let el;
ReactDOM.render(<Foobar ref={ref => el = ref} />, div);
doSomethingWith(el);
This is assuming that ref callbacks get called synchronously here.
setStateMixin using bluebird. It creates . this.setStateAsync for the current context, I wanted to run promisifyAll on the React prototype but it seems that React.createClass hides its prototypes which is sad.
import Promise from "bluebird";
export default {
componentWillMount() {
this.setStateAsync = Promise.promisify(this.setState);
},
};
import React from "react";
import Promise from "bluebird";
// ES6 class - have not tested this example (wrote it in the comment here) but should work
export default class Test extends React.Component {
constructor() {
super();
this.setStateAsync = Promise.promisify(this.setState);
}
}
so far this has worked fine in the situation of e.g.
{
handleDoSomething() {
return this.setStateAsync({
loading: true,
}).then(this.loadSomething).then((result) => {
return this.setStateAsync({result, loading: false});
});
}
}
This is really dirty, it will promisify the current context functions that includes reacts and your own. only use it when your lazy and not in production.
import Promise from "bluebird";
export default {
componentWillMount() {
Promise.promisifyAll(this);
},
};
@philikon
let el = ReactDOM.render(<Foobar />, div); doSomethingWith(el);becomes
let el; ReactDOM.render(<Foobar ref={ref => el = ref} />, div); doSomethingWith(el);
Wouldn't it be correct if it becomes
ReactDOM.render(
<Foobar />
).then((foobarRef) => {
doSomethingWith(foobarRef);
}).catch((error) => {
logCatchedRenderingError(error);
});
This way I have the opportunity to
- work with an ref as soon as the element was rendered
- catch rendering errors on specific components ... currently the whole app explodes if one component throws an error during rendering ...
- use promises for other functions (setState) as well
:+1: getting promises for state based changes would be a big plus for shallow testing component lifecycles
Would this be syntactically sound?: Promise.resolve( this.setState({ ... }) );
Using the bluebird Promise library.
+1 for this. since there is the possibility of a callback then it should be working with a promise. If it's an antipattern then remove the callback too.
:+ IF it doesn't add too much bloat.
How about this?
class AbstractComponent extends React.Component {
setStatePromise(newState) {
return new Promise((resolve) => {
this.setState(newState, () => {
resolve();
});
});
}
}
It's very useful to have an option to use promises instead of callbacks.
@spectrox Or you can avoid introducing a new base class entirely:
function setStatePromise(that, newState) {
return new Promise((resolve) => {
that.setState(newState, () => {
resolve();
});
});
}
I already had one, so, it was the simplest solution to add such function in it. And it's hard to add helper function (or mixin) in an ES6 environment, where every js file works in it's own scope, you'll have to import it everytime. So, it depends on an environment which option to choose 👍
+1 , I'd love the promise way.