-
Notifications
You must be signed in to change notification settings - Fork 562
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
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
113 changes: 113 additions & 0 deletions
113
text/0000-promise-returning-set-state-and-force-update.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. | ||
- 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? |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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-asyncThere was a problem hiding this comment.
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.There was a problem hiding this comment.
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, andsetState
always has to call a hidden callback to notify the object just in casepromise
was called. You still have to do all the same bookkeeping; the only difference is whether you make aPromise
instance or not.There was a problem hiding this comment.
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:
What if
.then
isn't called immediately (but is potentially called before it would have resolved)?There was a problem hiding this comment.
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)
.There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't see how that's possible unless
scheduleCallback
can be called after the update is already appliedThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Bingo :D