Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Promise-returning setState and forceUpdate #10

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 113 additions & 0 deletions text/0000-promise-returning-set-state-and-force-update.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
- Start Date: 2017-01-03
- RFC PR: (leave this empty)
- React Issue: (leave this empty)

# Summary

This RFC specifies `setState` and `forceUpdate` to return a promise when no
callback is provided.

# Basic example

```js
class DataFetcher extends React.Component {
state = {
loading: false,
error: null,
data: null,
};

async componentDidMount() {
await this.setState({ loading: true });
try {
let response = await fetch(this.props.url);
let data = await response.json();
await this.setState({ data, loading: false });
} catch (error) {
await this.setState({ error, loading: false });
}
};

render() {
return this.props.render(this.state);
}
}
```

Type definition:

```js
type Updater<State> = Partial<State> | (prevState: State) => Partial<State>;

declare class React.Component<Props, State> {
setState(updater: Updater<State>): Promise<void>;
setState(updater: Updater<State>, callback: () => mixed): void;
forceUpdate(): Promise<void>;
forceUpdate(callback: () => mixed): void;
// ...
}
```

# Motivation

- Promises are JavaScript's primitive for representing async activity
- Async-await is significantly easier to use than callback-based APIs
- Lots of new and existing APIs in the ecosystem and standards are moving towards
promises (ex: `fetch()`)
- As async-await becomes more available it will make more and more sense build with
- Developers are using `setState` as if it were sync today in lots of places which
end up needing to be refactored later on when new code needs the state to be applied before running

# Detailed design

When called with a callback, `setState` and `forceUpdate` will continue returning
`undefined`, when called without a callback it will return a promise which resolves
at the same time as the existing callback API.

```js
this.setState(updater, callback); // >> undefined
this.setState(updater); // >> promise
```

The reason for different return values is to avoid messy semantics supporting
the callback and promise simultaneously:

1. Would the callback be called before the promise resolves?
2. Does the promise wait for a promise returned by the callback?
3. What happens when the callback throws synchronously?

Instead, by only supporting promises when a callback is not provided, React
side-steps the problem entirely. There doesn't seem to be a use case where someone
would want both anyways.

# Drawbacks

- If `setState` without the callback is (or could be) optimized in anyway (due to not
needing the schedule the callback or something), it wouldn't be able to anymore because
the promise would always have to be returned.
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"Yes, we’d have to tag it as a node to visit when committing changes. setState() without callback doesn’t need that." – Dan

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Depending on how big of an impact this makes, I would consider this a big enough reason to reject this proposal outright.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It may be possible to detect if setState is declared async (which is not the same as returning a promise, true, but perhaps a good enough work-around?) - e.g. https://stackoverflow.com/questions/38508420/how-to-know-if-a-function-is-async

Copy link

@alexkrolick alexkrolick Jan 4, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some promisified callback APIs (like the AWS SDK) use a call to .promise() to know whether to ~~~return a Promise~~~ create a Promise.

await this.setState({ loading: true }).promise(); // awaitable/thenable

Copy link

@Jessidhia Jessidhia Jan 4, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That still means that you'd have to return an object that has a promise method, and setState always has to call a hidden callback to notify the object just in case promise was called. You still have to do all the same bookkeeping; the only difference is whether you make a Promise instance or not.

Copy link
Author

@jamiebuilds jamiebuilds Jan 5, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the bigger concern is more:

let thenable = this.setState({ ... });
setImmediate(() => {
  thenable.then(() => {
    // ...
  });
});

What if .then isn't called immediately (but is potentially called before it would have resolved)?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as calling this.setState(null, callback).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is that going to work as expected (i.e. the promise will resolve after the explicit setState finishes)? If so, could .then() always have those semantics?

If so, you could potentially only allocate at most a single thenable per component instance.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as calling this.setState(null, callback)

I don't see how that's possible unless scheduleCallback can be called after the update is already applied

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unless scheduleCallback can be called after the update is already applied

Bingo :D

- More API surface area (even if only temporarily)

# Alternatives

Unknown

# Adoption strategy

By supporting both the existing callback API and the promise-returning API, this
feature can be introduced in a minor version and supported indefinitely. If desired
the callback API can eventually start logging warnings and eventually removed in a
major version.

# How we teach this

(I believe) this would be the first place where promises are used within (major?)
React APIs, so teaching promises in the documentation might be necessary. Otherwise,
this API change doesn't change much so it can be taught the same way as it is today.

If React does eventually want to remove the callback API, that can be communicated
through deprecation warnings, blog posts, Dan Abramov tweets, etc.

# Unresolved questions

- Is `setState()` without the callback optimizable in any way that always having to
always return a promise would prevent?