Skip to content

Commit 89f580e

Browse files
committed
Cancel promise when promiseFn changes.
1 parent 24c10b6 commit 89f580e

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

src/index.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,10 @@ export const createInstance = (defaultProps = {}) => {
4646

4747
componentDidUpdate(prevProps) {
4848
if (prevProps.watch !== this.props.watch) this.load()
49+
if (prevProps.promiseFn !== this.props.promiseFn) {
50+
this.cancel()
51+
if (this.props.promiseFn) this.load()
52+
}
4953
}
5054

5155
componentWillUnmount() {

src/spec.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,17 @@ test("cancels pending promise when unmounted", async () => {
205205
expect(onResolve).not.toHaveBeenCalled()
206206
})
207207

208+
test("cancels and restarts the promise when promiseFn changes", async () => {
209+
const promiseFn1 = jest.fn().mockReturnValue(Promise.resolve("one"))
210+
const promiseFn2 = jest.fn().mockReturnValue(Promise.resolve("two"))
211+
const onResolve = jest.fn()
212+
const { rerender } = render(<Async promiseFn={promiseFn1} onResolve={onResolve} />)
213+
rerender(<Async promiseFn={promiseFn2} onResolve={onResolve} />)
214+
await Promise.resolve()
215+
expect(onResolve).not.toHaveBeenCalledWith("one")
216+
expect(onResolve).toHaveBeenCalledWith("two")
217+
})
218+
208219
test("does not run promiseFn on mount when initialValue is provided", () => {
209220
const promiseFn = jest.fn().mockReturnValue(Promise.resolve())
210221
render(<Async promiseFn={promiseFn} initialValue={{}} />)
@@ -376,7 +387,7 @@ test("createInstance allows setting default props", async () => {
376387
expect(onResolve).toHaveBeenCalledWith("done")
377388
})
378389

379-
test("An unrelated change in props does not update the Context", async () => {
390+
test("an unrelated change in props does not update the Context", async () => {
380391
let one
381392
let two
382393
const { rerender } = render(

0 commit comments

Comments
 (0)