Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions __tests__/subscriptions.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { createStore } from '../src'

describe('Subscriptions', () => {
const useStore = createStore('main', () => ({
name: 'Eduardo',
})).bind(null, true)

let store: ReturnType<typeof useStore>
beforeEach(() => {
store = useStore()
})

it('fires callback when patch is applied', () => {
const spy = jest.fn()
store.subscribe(spy)
store.state.name = 'Cleiton'
expect(spy).toHaveBeenCalledTimes(1)
})

it('unsubscribes callback when unsubscribe is called', () => {
const spy = jest.fn()
const unsubscribe = store.subscribe(spy)
unsubscribe()
store.state.name = 'Cleiton'
expect(spy).not.toHaveBeenCalled()
})

it('listeners are not affected when unsubscribe is called multiple times', () => {
const func1 = jest.fn()
const func2 = jest.fn()
const unsubscribe1 = store.subscribe(func1)
store.subscribe(func2)
unsubscribe1()
unsubscribe1()
store.state.name = 'Cleiton'
expect(func1).not.toHaveBeenCalled()
expect(func2).toHaveBeenCalledTimes(1)
})
})
9 changes: 7 additions & 2 deletions src/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,14 @@ export function buildStore<
})
}

function subscribe(callback: SubscriptionCallback<S>): void {
function subscribe(callback: SubscriptionCallback<S>) {
subscriptions.push(callback)
// TODO: return function to remove subscription
return () => {
const idx = subscriptions.indexOf(callback)
if (idx > -1) {
subscriptions.splice(idx, 1)
}
}
}

function reset() {
Expand Down
5 changes: 3 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,10 @@ export interface Store<Id extends string, S extends StateTree> {

/**
* Setups a callback to be called whenever the state changes.
* @param callback callback that is called whenever the state changes
* @param callback callback that is called whenever the state
* @returns function that removes callback from subscriptions
*/
subscribe(callback: SubscriptionCallback<S>): void
subscribe(callback: SubscriptionCallback<S>): () => void
}

export interface DevtoolHook {
Expand Down