Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changeset/readonly-store-bind.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/store': patch
---

Bind `get` and `subscribe` on `ReadonlyStore`, so they work when destructured, as they do on `Store`
4 changes: 4 additions & 0 deletions packages/store/src/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ export class ReadonlyStore<T> implements Omit<
this.atom = createAtom(
valueOrFn as T | ((prev?: NoInfer<T>) => T),
) as Atom<T>

// bind for safe destructuring
this.get = this.get.bind(this)
this.subscribe = this.subscribe.bind(this)
}
public get state() {
return this.atom.get()
Expand Down
14 changes: 14 additions & 0 deletions packages/store/tests/derived.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -291,4 +291,18 @@ describe('Derived', () => {
currentVal: 25,
})
})

test('get and subscribe should work when destructured', () => {
const count = createStore(1)
const { get, subscribe } = createStore(() => count.state * 2)
const fn = vi.fn()
const { unsubscribe } = subscribe(fn)

expect(get()).toBe(2)

count.setState(() => 2)
expect(fn).toHaveBeenCalledWith(4)

unsubscribe()
})
})