Skip to content

Commit

Permalink
make isEmpty an accessor so it reacts to value mutations
Browse files Browse the repository at this point in the history
  • Loading branch information
MZanggl committed Jan 5, 2020
1 parent 7afb4ad commit 7719cba
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
8 changes: 4 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,15 @@ function promistate<T>(action: (...args: CallbackArgs) => Promise<T>, options: P
return {
value: defaultValue,
isPending: false,
isEmpty: isEmpty<T>(defaultValue),
error: null,

get isEmpty() {
return this.isPending ? false : isEmpty(this.value)
},

reset() {
this.value = defaultValue
this.isPending = false
this.isEmpty = isEmpty<T>(defaultValue)
this.error = null
},

Expand All @@ -38,12 +40,10 @@ function promistate<T>(action: (...args: CallbackArgs) => Promise<T>, options: P
}

this.isPending = true
this.isEmpty = false
this.error = null

return action.apply(this, args)
.then((result: T) => {
this.isEmpty = isEmpty<T>(result)
this.value = result
this.isPending = false
return Status.RESOLVED
Expand Down
12 changes: 10 additions & 2 deletions test/promistate.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
Expand Down Expand Up @@ -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)
})

Expand Down Expand Up @@ -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)
})

0 comments on commit 7719cba

Please sign in to comment.