diff --git a/.changeset/readonly-store-bind.md b/.changeset/readonly-store-bind.md new file mode 100644 index 00000000..736ae8e7 --- /dev/null +++ b/.changeset/readonly-store-bind.md @@ -0,0 +1,5 @@ +--- +'@tanstack/store': patch +--- + +Bind `get` and `subscribe` on `ReadonlyStore`, so they work when destructured, as they do on `Store` diff --git a/packages/store/src/store.ts b/packages/store/src/store.ts index 69a91678..41f5c08f 100644 --- a/packages/store/src/store.ts +++ b/packages/store/src/store.ts @@ -69,6 +69,10 @@ export class ReadonlyStore implements Omit< this.atom = createAtom( valueOrFn as T | ((prev?: NoInfer) => T), ) as Atom + + // bind for safe destructuring + this.get = this.get.bind(this) + this.subscribe = this.subscribe.bind(this) } public get state() { return this.atom.get() diff --git a/packages/store/tests/derived.test.ts b/packages/store/tests/derived.test.ts index 436f1d78..10fcb9b5 100644 --- a/packages/store/tests/derived.test.ts +++ b/packages/store/tests/derived.test.ts @@ -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() + }) })