From 7719cba59606a9a01f1ab581bcf6ed690eeef0fa Mon Sep 17 00:00:00 2001 From: Michael Date: Sun, 5 Jan 2020 15:01:42 +0900 Subject: [PATCH] make isEmpty an accessor so it reacts to value mutations --- src/index.ts | 8 ++++---- test/promistate.spec.js | 12 ++++++++++-- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/index.ts b/src/index.ts index 311fd7f..986cb7a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -22,13 +22,15 @@ function promistate(action: (...args: CallbackArgs) => Promise, options: P return { value: defaultValue, isPending: false, - isEmpty: isEmpty(defaultValue), error: null, + get isEmpty() { + return this.isPending ? false : isEmpty(this.value) + }, + reset() { this.value = defaultValue this.isPending = false - this.isEmpty = isEmpty(defaultValue) this.error = null }, @@ -38,12 +40,10 @@ function promistate(action: (...args: CallbackArgs) => Promise, options: P } this.isPending = true - this.isEmpty = false this.error = null return action.apply(this, args) .then((result: T) => { - this.isEmpty = isEmpty(result) this.value = result this.isPending = false return Status.RESOLVED diff --git a/test/promistate.spec.js b/test/promistate.spec.js index fc1b7f7..f5cfbe9 100644 --- a/test/promistate.spec.js +++ b/test/promistate.spec.js @@ -83,7 +83,7 @@ test('catches errors', async (assert) => { assert.equal(state.error.message, 'blub') assert.isFalse(state.isPending) - assert.isFalse(state.isEmpty) + assert.isTrue(state.isEmpty) assert.isNull(state.value) assert.equal(status, Status.ERROR) }) @@ -117,7 +117,7 @@ test('does throw error when option is set to let it bubble up', async (assert) = assert.equal(state.error.message, 'blub') assert.isFalse(state.isPending) - assert.isFalse(state.isEmpty) + assert.isTrue(state.isEmpty) assert.isNull(state.value) }) @@ -163,3 +163,11 @@ test('can access state in load function', async (assert) => { assert.equal(state.value, 2) }) + +test('isEmpty reacts to value changes', async (assert) => { + const state = promistate(() => [], { defaultValue: [1] }) + assert.isFalse(state.isEmpty) + + state.value = [] + assert.isTrue(state.isEmpty) +})