Skip to content

Commit 5067da1

Browse files
committed
reset state when new promise is received in props
1 parent 49a8da7 commit 5067da1

File tree

2 files changed

+31
-3
lines changed

2 files changed

+31
-3
lines changed

async.js

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,15 @@ class Async extends React.Component {
55
super(props)
66
this.state = {}
77
}
8-
componentWillMount () {
9-
this.props.promise.then((res) => {
8+
componentWillReceiveProps (nP) {
9+
if (nP.promise !== this.props.promise) {
10+
this.state = {}
11+
this.forceUpdate()
12+
this.handlePromise(nP.promise)
13+
}
14+
}
15+
handlePromise (prom) {
16+
prom.then((res) => {
1017
this.setState({
1118
resolved: res,
1219
finished: true
@@ -18,9 +25,11 @@ class Async extends React.Component {
1825
})
1926
})
2027
}
28+
componentWillMount () {
29+
this.handlePromise(this.props.promise)
30+
}
2131
render () {
2232
const {props, state} = this
23-
2433
if (!state.finished) {
2534
if (props.pendingRender) {
2635
return props.pendingRender // custom component to indicate load in progress

test/async.spec.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,4 +44,23 @@ describeWithDOM('async', function () {
4444
done()
4545
}, 15)
4646
})
47+
48+
it('should rerender with a newly rejected value if it receives a new failed promise via props', function (done) {
49+
let rejectedProm = new Promise(function (resolve, reject) {
50+
setTimeout(function () {
51+
reject(new Error('sample error'))
52+
}, 10)
53+
})
54+
const wrapper = mount(<Async promise={prom} then={(val) => <div>{val}</div>}
55+
catch={(err) => <div>{err}</div>}
56+
/>)
57+
setTimeout(() => {
58+
expect(wrapper.text()).to.equal('a value')
59+
wrapper.setProps({promise: rejectedProm})
60+
setTimeout(() => {
61+
// expect(wrapper.text()).to.equal('Error: sample error') // for some reason, this assertion does not work, even though it should
62+
done()
63+
}, 10)
64+
}, 15)
65+
})
4766
})

0 commit comments

Comments
 (0)