Skip to content
This repository was archived by the owner on Jun 17, 2019. It is now read-only.

Commit bb05234

Browse files
author
Josef Blake
committed
remove unecessary rerender
add support for non-promise values
1 parent a7bbef9 commit bb05234

File tree

3 files changed

+20
-9
lines changed

3 files changed

+20
-9
lines changed
File renamed without changes.

__tests__/Async.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,22 +19,22 @@ afterEach(() => {
1919
ReactDOM.unmountComponentAtNode(mountNode);
2020
});
2121

22-
test("renders", () => {
22+
test("renders (default)", () => {
2323
expect(() => mount(<Async />)).not.toThrowError();
2424
});
2525

26-
test("throws error if not passed a promise", () => {
26+
test("supports non-promise values", () => {
2727
const onError = jest.fn();
2828

29-
[1, {}, [], null].forEach(notPromise => {
29+
[1, {}, [], undefined, null].forEach(notPromise => {
3030
mount(
3131
<ErrorBoundary onError={onError}>
3232
<Async await={notPromise} />
3333
</ErrorBoundary>
3434
);
3535
});
3636

37-
expect(onError).toHaveBeenCalledTimes(4);
37+
expect(onError).toHaveBeenCalledTimes(0);
3838
});
3939

4040
test("resolves promise", async () => {

src/Async.js

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,18 @@
11
import React from "react";
22

3+
const isPromise = promise => promise && typeof promise.then === "function";
4+
35
const cache = new WeakMap();
46

57
const getCachedState = promise => {
8+
if (!isPromise(promise)) {
9+
return {
10+
status: 1,
11+
value: promise,
12+
error: undefined
13+
};
14+
}
15+
616
if (!cache.has(promise)) {
717
const result = {
818
status: 0,
@@ -43,10 +53,12 @@ class Async extends React.Component {
4353
subscribed = false;
4454
};
4555

46-
this.props.await.then(
47-
() => subscribed && this.componentWillMount(),
48-
() => subscribed && this.componentWillMount()
49-
);
56+
if (this.state.status === 0) {
57+
this.props.await.then(
58+
() => subscribed && this.componentWillMount(),
59+
() => subscribed && this.componentWillMount()
60+
);
61+
}
5062
}
5163

5264
componentDidUpdate(prevProps) {
@@ -73,7 +85,6 @@ class Async extends React.Component {
7385
}
7486

7587
Async.defaultProps = {
76-
await: Promise.resolve(),
7788
children: () => null
7889
};
7990

0 commit comments

Comments
 (0)