feat(core) atom.whileWatched (useEffect-like primitive) and createExternalStoreAtom #312
main fromrefs/pull/312/head·opened 🎯 Changes#
Add atom.whileWatched(cb), store.whileWatched(cb), and createExternaStoreAtom.
atom.whileWatched allows running a setup function when the atom gains its first subscriber, and optionally running the cleanup function returned by setup when the atom loses its last subscriber.
This gives us a useLayoutEffect-like primitive that we build createExternalStoreAtom on top of.
Example use case of these features is to implement a createQueryAtom function to pull @tanstack/query-core state into the @tanstack/store reactivity graph. We use this primitive at Notion Labs Inc for this purpose.
You can also use this primitive to build atoms that automatically sync their state across tabs via localStorage, etc
import { type QueryClient, type QueryObserverOptions, QueryObserver } from '@tanstack/query-core'
import { createExternalStoreAtom } from '@tanstack/store'
import { queryClient } from "./queryClient"
export function createQueryAtom<TData, TError = Error>(
queryClient: QueryClient,
options: QueryObserverOptions<TData, TError, TData, TData, readonly unknown[]>,
) {
const observer = new QueryObserver<TData, TError>(queryClient, options)
return createExternalStoreAtom(
() => observer.getCurrentResult(),
(onChange) => observer.subscribe(onChange),
)
}
// Example
const userQuery = createQueryAtom<{ id: number; name: string }>(queryClient, {
queryKey: ['user', 1],
queryFn: async () => {
const res = await fetch('/api/user/1')
return res.json()
},
})
// No fetch yet — nobody's observing.
const sub = userQuery.subscribe((result) => {
if (result.isPending) console.log('loading…')
else if (result.error) console.error('failed:', result.error)
else console.log('user:', result.data)
})
// First subscribe → whileWatched fires → observer.subscribe → fetch kicks off.
// Read the current state any time, even synchronously from elsewhere:
console.log(userQuery.get().data)
// Later…
sub.unsubscribe()
// Last unsubscriber → observer.unsubscribe runs → after gcTime, query is evicted.
✅ Checklist#
- I have followed the steps in the Contributing guide.
- I have tested this code locally with
pnpm test:pr.
🚀 Release Impact#
- This change affects published code, and I have generated a changeset.
- This change is docs/CI/dev-only (no release).
Summary by CodeRabbit#
Release Notes#
New Features
- Added
whileWatched()method to atoms and stores, enabling effects that activate during observation and cleanup when unwatched. - Introduced
createExternalStoreAtomto synchronize external store state with atoms automatically.
- Added
Documentation
- Updated API reference navigation with entries for new functionality.
- 1
justjake(GitHub profile, opens in a new tab) changed the title
Actionable comments posted: 7
🧹 Nitpick comments (1)
packages/store/tests/while-watched.test.ts (1)
103-124: Add astop()-while-watched test case.Current
stop()tests cover idempotency and future activations, but not cancellation during an active watch. Add a case wherestop()is called before unsubscribing and assert cleanup runs immediately and only once.Suggested test addition
test('stop() is idempotent', () => { const atom = createAtom(0) const stop = atom.whileWatched(() => {}) expect(() => { stop() stop() }).not.toThrow() }) + +test('stop() while watched runs cleanup immediately and only once', () => { + const atom = createAtom(0) + const cleanup = vi.fn() + const stop = atom.whileWatched(() => cleanup) + const sub = atom.subscribe(() => {}) + + stop() + expect(cleanup).toHaveBeenCalledTimes(1) + + sub.unsubscribe() + expect(cleanup).toHaveBeenCalledTimes(1) +})🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/store/tests/while-watched.test.ts` around lines 103 - 124, Add a new test to verify that calling stop() during an active watch cancels immediately and runs cleanup exactly once: create an atom via createAtom(0), call atom.whileWatched(effect) to get stop, ensure the effect was invoked once after subscribing (use atom.subscribe(() => {}) and keep the subscription active), then call stop() before unsubscribing and assert the cleanup/effect-run count increments exactly once and that subsequent unsubscribe does not call the cleanup again; reference the whileWatched method and the returned stop function and use a vi.fn() for effect to assert exact call counts.🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed. Inline comments: In `@docs/reference/functions/createExternalStoreAtom.md`: - Line 15: The "Defined in" link for createExternalStoreAtom points to a fork URL; update the link in docs/reference/functions/createExternalStoreAtom.md (the "Defined in" line) to use the canonical main repository path pointing to atom.ts at the correct location (referenced symbol: createExternalStoreAtom / atom.ts:190) so the documentation links to the upstream repo instead of the fork. - Around line 17-36: Fix the markdown by closing the open code fence for the example and correcting the typo: change "Thic" to "This" in the description for createExternalStoreAtom and add a terminating triple backtick (```) immediately before the "## Type Parameters" heading so the example block ends properly. In `@docs/reference/type-aliases/WatchedEffect.md`: - Line 12: Update the "Defined in" link in docs/reference/type-aliases/WatchedEffect.md so it points to the project's canonical repository URL instead of the fork; locate the "Defined in: [atom.ts:33](...)" line and replace the current forked GitHub URL with the main repo URL that matches the package source (referencing atom.ts line 33) so future readers get the authoritative source reference. - Around line 9-10: The documented type signature for WatchedEffect is wrong: update the rendered signature to indicate the callback may return either a cleanup function (() => void), void, or undefined (i.e., (() => void) | void | undefined) so it doesn't imply a function is always returned; change the WatchedEffect documentation and any other occurrences (notably the similar entries around lines 17-19) to use that corrected union form and ensure the prose matches this behavior. In `@packages/store/src/atom.ts`: - Around line 171-173: The JSDoc for the exported API describing the "pulls external state into an atom" behavior has a typo ("Thic"); update the comment text to read "This can be used..." in the JSDoc block that documents the external-state-to-atom utility (the comment above the function that implements the useSyncExternalStore-like atom behavior) so the public docs are correct. - Around line 265-273: stop() currently only removes the listener from atom._watchedSubs but does not invoke any active cleanup when atom._watched is true; update stop() so that when removing the listener it also runs and clears the listener's active cleanup (e.g. call listener._cleanup() or listener.cleanup() if present and then delete that property), and if removing the last watched subscriber set atom._watched to false and invoke/clear any atom-level cleanup (atom._cleanup) as needed; reference the stop() function, atom._watchedSubs, atom._watched, listener._cleanup / listener.cleanup, and atom._cleanup to locate and implement these changes. In `@packages/store/src/types.ts`: - Line 40: Fix the minor grammar in the API doc comment for the return value of the whileWatched-related type by changing "an `cleanup` function" to "a `cleanup` function"; update the doc comment that describes the return value for the whileWatched listener (the text mentioning `cleanup`) so it reads "a `cleanup` function" instead of "an `cleanup`". --- Nitpick comments: In `@packages/store/tests/while-watched.test.ts`: - Around line 103-124: Add a new test to verify that calling stop() during an active watch cancels immediately and runs cleanup exactly once: create an atom via createAtom(0), call atom.whileWatched(effect) to get stop, ensure the effect was invoked once after subscribing (use atom.subscribe(() => {}) and keep the subscription active), then call stop() before unsubscribing and assert the cleanup/effect-run count increments exactly once and that subsequent unsubscribe does not call the cleanup again; reference the whileWatched method and the returned stop function and use a vi.fn() for effect to assert exact call counts.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
c7ec2563-56c3-4ec7-a40b-106287ae95e8📥 Commits
Reviewing files that changed from the base of the PR and between 83e2978f627ec53616249b2bda1037749b18b6ab and 5e144d18fa3d6c1244e29a84a1750fe9713ab12d.
📒 Files selected for processing (11)
.changeset/ninety-actors-hide.mddocs/config.jsondocs/reference/functions/createExternalStoreAtom.mddocs/reference/type-aliases/WatchedEffect.mdpackages/store/src/alien.tspackages/store/src/atom.tspackages/store/src/signal.tspackages/store/src/store.tspackages/store/src/types.tspackages/store/tests/external-store-atom.test.tspackages/store/tests/while-watched.test.ts
docs/reference/functions/createExternalStoreAtom.md line 15OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,15 @@1+---2+id: createExternalStoreAtom3+title: createExternalStoreAtom4+---5+6+# Function: createExternalStoreAtom()7+8+```ts9+function createExternalStoreAtom<T>(10+ getSnapshot,11+ subscribe,12+options?): ReadonlyAtom<T>;13+```14+15+Defined in: [atom.ts:190](https://github.com/justjake/store/blob/main/packages/store/src/atom.ts#L190)⚠️ Potential issue | 🟡 Minor
Use canonical repository link in “Defined in”.
Line 15 should reference the main project repo path rather than a fork URL.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@docs/reference/functions/createExternalStoreAtom.md` at line 15, The "Defined in" link for createExternalStoreAtom points to a fork URL; update the link in docs/reference/functions/createExternalStoreAtom.md (the "Defined in" line) to use the canonical main repository path pointing to atom.ts at the correct location (referenced symbol: createExternalStoreAtom / atom.ts:190) so the documentation links to the upstream repo instead of the fork.✅ Addressed in commit 768b8b5
docs/reference/functions/createExternalStoreAtom.md lines 17 to 36OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +16,21 @@16+17+Like React.useSyncExternalStore: pulls external state into an atom.18+Thic can be used for interoperating with other state management libraries.19+20+```ts21+import * as redux from "redux"22+23+const reduxStore = redux.createStore((state: number, action: number) => state + action, 0)24+const atom = createExternalStoreAtom(reduxStore.getState, reduxStore.subscribe)25+26+const timesTwo = createAtom(() => atom.get() * 2)27+timesTwo.subscribe((value) => {28+ console.log('timesTwo: ', value)29+})30+31+reduxStore.dispatch(1)32+// timesTwo: 233+reduxStore.dispatch(1)34+// timesTwo: 435+36+## Type Parameters⚠️ Potential issue | 🟠 Major
Close the example code fence before the next section.
The code block opened at Line 20 is not closed before “## Type Parameters” (Line 36), which breaks page rendering. Also fix “Thic” → “This” in Line 18.
🧩 Proposed markdown fix
Like React.useSyncExternalStore: pulls external state into an atom. -Thic can be used for interoperating with other state management libraries. +This can be used for interoperating with other state management libraries. ... reduxStore.dispatch(1) // timesTwo: 4 +``` ## Type Parameters🧰 Tools
🪛 LanguageTool
[grammar] ~17-~17: Ensure spelling is correct Context: ...ore: pulls external state into an atom. Thic can be used for interoperating with oth...
(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@docs/reference/functions/createExternalStoreAtom.md` around lines 17 - 36, Fix the markdown by closing the open code fence for the example and correcting the typo: change "Thic" to "This" in the description for createExternalStoreAtom and add a terminating triple backtick (```) immediately before the "## Type Parameters" heading so the example block ends properly.✅ Addressed in commits 7e47c65 to 1b5acd1
@@ -0,0 +1,10 @@1+---2+id: WatchedEffect3+title: WatchedEffect4+---5+6+# Type Alias: WatchedEffect()7+8+```ts9+type WatchedEffect = () => () => void | void | undefined;10+```⚠️ Potential issue | 🟡 Minor
Type signature rendering is inaccurate.
The doc currently implies the callback always returns a function. It should reflect
(() => void) | void | undefined.🛠️ Proposed signature/returns fix
-type WatchedEffect = () => () => void | void | undefined; +type WatchedEffect = () => (() => void) | void | undefined; ... -() => `void` \| `void` \| `undefined` +(() => `void`) \| `void` \| `undefined`Also applies to: 17-19
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@docs/reference/type-aliases/WatchedEffect.md` around lines 9 - 10, The documented type signature for WatchedEffect is wrong: update the rendered signature to indicate the callback may return either a cleanup function (() => void), void, or undefined (i.e., (() => void) | void | undefined) so it doesn't imply a function is always returned; change the WatchedEffect documentation and any other occurrences (notably the similar entries around lines 17-19) to use that corrected union form and ensure the prose matches this behavior.docs/reference/type-aliases/WatchedEffect.md line 12OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,12 @@1+---2+id: WatchedEffect3+title: WatchedEffect4+---5+6+# Type Alias: WatchedEffect()7+8+```ts9+type WatchedEffect = () => () => void | void | undefined;10+```11+12+Defined in: [atom.ts:33](https://github.com/justjake/store/blob/main/packages/store/src/atom.ts#L33)⚠️ Potential issue | 🟡 Minor
Use canonical repository link in “Defined in”.
Line 12 points to a fork URL; switch to the project’s canonical repo link to avoid stale source references.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@docs/reference/type-aliases/WatchedEffect.md` at line 12, Update the "Defined in" link in docs/reference/type-aliases/WatchedEffect.md so it points to the project's canonical repository URL instead of the fork; locate the "Defined in: [atom.ts:33](...)" line and replace the current forked GitHub URL with the main repo URL that matches the package source (referencing atom.ts line 33) so future readers get the authoritative source reference.✅ Addressed in commit 768b8b5
packages/store/src/atom.ts lines 303 to 305Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -135,3 +167,7 @@135167 return atom136168 }137169170+/**171+ * Like React.useSyncExternalStore: pulls external state into an atom.172+ * Thic can be used for interoperating with other state management libraries.173+ *⚠️ Potential issue | 🟡 Minor
Fix JSDoc typo in public API docs.
Line 172 says “Thic can be used...”; this should be “This can be used...”.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/store/src/atom.ts` around lines 171 - 173, The JSDoc for the exported API describing the "pulls external state into an atom" behavior has a typo ("Thic"); update the comment text to read "This can be used..." in the JSDoc block that documents the external-state-to-atom utility (the comment above the function that implements the useSyncExternalStore-like atom behavior) so the public docs are correct.✅ Addressed in commits 7e47c65 to 000d6bf
packages/store/src/atom.ts lines 265 to 273OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -185,3 +254,20 @@185254 },186255 }187256 },257+258+ whileWatched(listener: WatchedEffect): () => void {259+ atom._watchedSubs ??= []260+ atom._watchedSubs.push(listener)261+ if (atom._watched) {262+ atom._watchedCleanups ??= []263+ atom._watchedCleanups.push(listener())264+ }265+ return () => {266+ if (!atom._watchedSubs) {267+ return268+ }269+ const index = atom._watchedSubs.indexOf(listener)270+ if (index !== -1) {271+ atom._watchedSubs.splice(index, 1)272+ }273+ }⚠️ Potential issue | 🟠 Major
stop()does not clean up active watchers, causing leaks while still watched.On Line 265–Line 273,
stop()removes the listener from_watchedSubsbut does not run/remove its active cleanup when_watched === true. This can leave resources (e.g. external subscriptions) active until full unwatch.Proposed fix
whileWatched(listener: WatchedEffect): () => void { atom._watchedSubs ??= [] atom._watchedSubs.push(listener) if (atom._watched) { atom._watchedCleanups ??= [] atom._watchedCleanups.push(listener()) } return () => { if (!atom._watchedSubs) { return } const index = atom._watchedSubs.indexOf(listener) if (index !== -1) { atom._watchedSubs.splice(index, 1) + if (atom._watched && atom._watchedCleanups) { + const [cleanup] = atom._watchedCleanups.splice(index, 1) + cleanup?.() + } } } },🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/store/src/atom.ts` around lines 265 - 273, stop() currently only removes the listener from atom._watchedSubs but does not invoke any active cleanup when atom._watched is true; update stop() so that when removing the listener it also runs and clears the listener's active cleanup (e.g. call listener._cleanup() or listener.cleanup() if present and then delete that property), and if removing the last watched subscriber set atom._watched to false and invoke/clear any atom-level cleanup (atom._cleanup) as needed; reference the stop() function, atom._watchedSubs, atom._watched, listener._cleanup / listener.cleanup, and atom._cleanup to locate and implement these changes.✅ Addressed in commits 3e00449 to 7ccd188
It would be a bug to remove / fire the teardown function when removing the setup subscriber.
@justjake, understood — thank you for the clarification. The design intent is thatstop()only de-registers the effect from future watch cycles; the current cycle's cleanup still lives in_watchedCleanupsand fires naturally when the atom loses its last subscriber via theunwatchedhook. Firing the teardown eagerly instop()would incorrectly cancel a still-active subscription mid-watch. I'll retract the suggestion.(◕‿◕✿)
✏️ Learnings added
Learnt from: justjake Repo: TanStack/store PR: 312 File: packages/store/src/atom.ts:265-273 Timestamp: 2026-04-17T17:42:08.842Z Learning: In `packages/store/src/atom.ts` (TanStack Store), the `stop()` function returned by `atom.whileWatched(listener)` is intentionally designed to only remove the listener from `_watchedSubs` (preventing future re-registration) without firing or removing the active cleanup from `_watchedCleanups`. The current cycle's cleanup remains in `_watchedCleanups` and is called naturally when the atom becomes unwatched (via the `unwatched` hook calling `_watchedCleanups.forEach`). Eagerly running the cleanup in `stop()` would be a bug, as the subscription should stay active for the duration of the current watched period.Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
packages/store/src/types.ts line 40OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -30,4 +31,10 @@3031 get: () => T3132 }323333-export interface BaseAtom<T> extends Subscribable<T>, Readable<T> {}34+export interface BaseAtom<T> extends Subscribable<T>, Readable<T> {35+ /**36+ * `effect` will be called when the first subscriber is added. `effect`37+ * may return a cleanup function, which will be called when the atom is38+ * unwatched.39+ *40+ * Returns an `cleanup` function which removes the `whileWatched` listener.⚠️ Potential issue | 🟡 Minor
Fix article typo in API doc comment.
Line 40 should read “a
cleanupfunction” (not “ancleanup”).✏️ Proposed doc fix
- * Returns an `cleanup` function which removes the `whileWatched` listener. + * Returns a `cleanup` function which removes the `whileWatched` listener.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/store/src/types.ts` at line 40, Fix the minor grammar in the API doc comment for the return value of the whileWatched-related type by changing "an `cleanup` function" to "a `cleanup` function"; update the doc comment that describes the return value for the whileWatched listener (the text mentioning `cleanup`) so it reads "a `cleanup` function" instead of "an `cleanup`".✅ Addressed in commits 7e47c65 to 1b5acd1
Actionable comments posted: 1
♻️ Duplicate comments (1)
packages/store/src/atom.ts (1)
258-273: ⚠️ Potential issue | 🟠 MajorStopping an active
whileWatchedlistener still leaves its cleanup running.When
stop()is called after Line 263 has registered a cleanup, Lines 269-271 remove the listener from_watchedSubsbut never remove or invoke the matching entry in_watchedCleanups. The external resource stays live until fullunwatched(), and the cleanup array can drift out of index alignment with the listener array.Proposed fix
whileWatched(listener: WatchedEffect): () => void { atom._watchedSubs ??= [] atom._watchedSubs.push(listener) if (atom._watched) { atom._watchedCleanups ??= [] atom._watchedCleanups.push(listener()) } return () => { if (!atom._watchedSubs) { return } const index = atom._watchedSubs.indexOf(listener) if (index !== -1) { atom._watchedSubs.splice(index, 1) + if (atom._watched && atom._watchedCleanups) { + const [cleanup] = atom._watchedCleanups.splice(index, 1) + cleanup?.() + } } } },🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/store/src/atom.ts` around lines 258 - 273, The unsubscribe returned by whileWatched currently removes the listener from atom._watchedSubs but leaves the corresponding entry in atom._watchedCleanups, causing the cleanup to keep running and arrays to drift; update the returned function in whileWatched to locate the listener index, remove the same index from atom._watchedCleanups (if present), and invoke the stored cleanup function (or safely skip if undefined) so the external resource is released immediately; ensure this logic references atom._watchedSubs, atom._watchedCleanups, and the listener returned by whileWatched and preserves behavior when atom._watched is false or when unwatched() later runs.🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed. Inline comments: In `@packages/store/src/atom.ts`: - Around line 195-203: The computed atom is calling trigger.get() inside its read which creates a persistent dependency (trigger -> atom) and keeps subscribe(invalidate) active; change the implementation so the computed read does not perform a subscribing get on trigger. Replace the subscribing read (trigger.get()) with a non-subscribing peek/read (or an equivalent API) so the computed returns getSnapshot() without creating the dependency, or move the subscribe(invalidate) logic into the returned atom's whileWatched handler (use trigger.whileWatched / the atom's whileWatched) so subscription to the external store is only established when the returned atom itself is observed; reference trigger, invalidate, trigger.whileWatched, createAtom, and getSnapshot when making the change. --- Duplicate comments: In `@packages/store/src/atom.ts`: - Around line 258-273: The unsubscribe returned by whileWatched currently removes the listener from atom._watchedSubs but leaves the corresponding entry in atom._watchedCleanups, causing the cleanup to keep running and arrays to drift; update the returned function in whileWatched to locate the listener index, remove the same index from atom._watchedCleanups (if present), and invoke the stored cleanup function (or safely skip if undefined) so the external resource is released immediately; ensure this logic references atom._watchedSubs, atom._watchedCleanups, and the listener returned by whileWatched and preserves behavior when atom._watched is false or when unwatched() later runs.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
205a6861-ba8c-4c99-a55a-3827fb328d5b📥 Commits
Reviewing files that changed from the base of the PR and between 5e144d18fa3d6c1244e29a84a1750fe9713ab12d and 1b5acd129dac1c0d7755dab18efcf9448226a10e.
📒 Files selected for processing (2)
packages/store/src/atom.tspackages/store/src/types.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/store/src/types.ts
packages/store/src/atom.ts lines 328 to 334Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -137,0 +183,21 @@183+ * })184+ *185+ * reduxStore.dispatch(1)186+ * // timesTwo: 2187+ * reduxStore.dispatch(1)188+ * // timesTwo: 4189+ */190+export function createExternalStoreAtom<T>(191+ getSnapshot: () => T,192+ subscribe: (onStoreChange: () => void) => () => void,193+ options?: AtomOptions<T>,194+): ReadonlyAtom<T> {195+ const trigger = createAtom(0)196+ const invalidate = () => trigger.set((n) => n + 1)197+ trigger.whileWatched(() => subscribe(invalidate))198+199+ return createAtom(() => {200+ // Return latest snapshot when `trigger` changes201+ trigger.get()202+ return getSnapshot()203+ }, options)⚠️ Potential issue | 🟠 Major
Plain
get()can keep the external store subscribed indefinitely.Line 201 tracks
triggerfrom inside a computed atom. Because computed reads run withactiveSub = atom, a one-offatom.get()still creates atrigger -> atomdependency, andpackages/store/src/alien.tscallswatched(dep)on that first link. Since that link is only removed when the dependency graph is later purged, Line 197 can leavesubscribe(invalidate)active even when the external atom has no subscribers. That breaks the “subscribe only while observed” contract.Consider avoiding
trigger.get()for unobserved reads, or backing this with a mutable atom that readsgetSnapshot()on demand and only subscribes viaatom.whileWatched.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/store/src/atom.ts` around lines 195 - 203, The computed atom is calling trigger.get() inside its read which creates a persistent dependency (trigger -> atom) and keeps subscribe(invalidate) active; change the implementation so the computed read does not perform a subscribing get on trigger. Replace the subscribing read (trigger.get()) with a non-subscribing peek/read (or an equivalent API) so the computed returns getSnapshot() without creating the dependency, or move the subscribe(invalidate) logic into the returned atom's whileWatched handler (use trigger.whileWatched / the atom's whileWatched) so subscription to the external store is only established when the returned atom itself is observed; reference trigger, invalidate, trigger.whileWatched, createAtom, and getSnapshot when making the change.✅ Addressed in commits 3e00449 to 7ccd188
Actionable comments posted: 2
♻️ Duplicate comments (1)
packages/store/src/atom.ts (1)
196-203: ⚠️ Potential issue | 🟠 MajorAvoid subscribing the external store on plain
get().Line 202 still creates the
trigger -> atomdependency during computed evaluation. A one-offatom.get()can therefore marktriggeras watched and keepsubscribe(invalidate)active even though the returned atom has no subscribers, which breaks the “only while watched” contract.Move the subscription to the returned atom
export function createExternalStoreAtom<T>( getSnapshot: () => T, subscribe: (onStoreChange: () => void) => () => void, options?: AtomOptions<T>, ): ReadonlyAtom<T> { const trigger = createAtom(0) const invalidate = () => trigger.set((n) => n + 1) - trigger.whileWatched(() => subscribe(invalidate)) - - return createAtom(() => { + const atom = createAtom(() => { // Return latest snapshot when `trigger` changes trigger.get() return getSnapshot() }, options) + atom.whileWatched(() => subscribe(invalidate)) + return atom }🧹 Nitpick comments (1)
packages/store/src/atom.ts (1)
41-47: Clarify thatstop()only affects future watch cycles.“Returns a
stopfunction which cancels the listener” reads like immediate teardown, but the implementation intentionally keeps the current cycle active and only prevents future re-registration. Tightening the wording here would make the public contract much clearer.Based on learnings: In
packages/store/src/atom.ts,stop()is intentionally limited to removing the listener from future watch cycles and must not fire or remove the current cycle’s cleanup.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/store/src/atom.ts` around lines 41 - 47, The docstring for whileWatched (type: (effect: WatchedEffect) => () => void) is misleading: change the return description to state that the returned stop() only prevents the provided effect from being re-registered in future watch cycles and does not invoke the current cycle’s cleanup or remove the active listener immediately; reference the whileWatched signature and WatchedEffect type, and explicitly note that existing active effect cleanup will still run only when the current watch cycle ends.🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed. Inline comments: In `@packages/store/src/atom.ts`: - Around line 259-273: The stop closure removes the first matching listener via indexOf, which breaks when the same listener was registered multiple times; change the registration to capture the cleanup return and have the stopper remove the most recently added matching entries using lastIndexOf: when pushing to atom._watchedSubs, capture the pushed listener (or its index) and when you push the cleanup (listener()) capture that cleanup value into a local (e.g., cleanupRef), then in the returned stop() use atom._watchedSubs.lastIndexOf(listener) to find and splice the correct (most recent) subscriber and use atom._watchedCleanups.lastIndexOf(cleanupRef) to remove the corresponding cleanup entry. Ensure you only attempt to remove when the found index !== -1. - Around line 66-79: The watched/unwatched lifecycle must be made exception-safe: in watched(InternalAtom) initialize atom._watchedCleanups = [] before running any setup and then iterate atom._watchedSubs (not using map) calling each setup in a try block and pushing its returned cleanup (if any) into atom._watchedCleanups; if a setup throws, ensure atom._watchedCleanups remains set with already-collected cleanup functions and rethrow the error. In unwatched(InternalAtom) iterate atom._watchedCleanups and invoke each cleanup inside its own try/catch so one throwing cleanup does not prevent others from running, then always clear atom._watchedCleanups.length = 0 and set atom._watched = false. --- Nitpick comments: In `@packages/store/src/atom.ts`: - Around line 41-47: The docstring for whileWatched (type: (effect: WatchedEffect) => () => void) is misleading: change the return description to state that the returned stop() only prevents the provided effect from being re-registered in future watch cycles and does not invoke the current cycle’s cleanup or remove the active listener immediately; reference the whileWatched signature and WatchedEffect type, and explicitly note that existing active effect cleanup will still run only when the current watch cycle ends.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
b7e509ae-343a-43a4-812a-b08512fff464📥 Commits
Reviewing files that changed from the base of the PR and between 1b5acd129dac1c0d7755dab18efcf9448226a10e and 6dc28fbcf83981a35dd686c7bb56393f4b6e315a.
📒 Files selected for processing (1)
packages/store/src/atom.ts
packages/store/src/atom.ts lines 66 to 79OutdatedResolvedby justjake(GitHub profile, opens in a new tab)@@ -45,4 +63,17 @@4563 queuedEffects[queuedEffectsLength++] = effect4664 effect.flags &= ~ReactiveFlags.Watching4765 },66+ watched(atom: InternalAtom<any>): void {67+ atom._watched = true68+ if (atom._watchedSubs?.length) {69+ atom._watchedCleanups = atom._watchedSubs.map((sub) => sub())70+ }71+ },4872 unwatched(atom: InternalAtom<any>): void {73+ atom._watched = false74+ // not sure if this should go above or below the deps purge75+ // preorder vs postorder76+ if (atom._watchedCleanups?.length) {77+ atom._watchedCleanups.forEach((cleanup) => cleanup?.())78+ atom._watchedCleanups.length = 079+ }⚠️ Potential issue | 🟠 Major
Make watched lifecycle callbacks exception-safe.
Line 69 assigns
_watchedCleanupsonly after every setup succeeds, so one throwing setup loses the cleanups returned by earlier setups. Line 77 also stops on the first throwing cleanup, which skips later teardowns and can leave external subscriptions/resources behind.Suggested hardening
watched(atom: InternalAtom<any>): void { atom._watched = true if (atom._watchedSubs?.length) { - atom._watchedCleanups = atom._watchedSubs.map((sub) => sub()) + const cleanups: Array<(() => void) | void | undefined> = [] + try { + for (const sub of atom._watchedSubs) { + cleanups.push(sub()) + } + atom._watchedCleanups = cleanups + } catch (error) { + atom._watched = false + for (const cleanup of cleanups) { + cleanup?.() + } + throw error + } } }, unwatched(atom: InternalAtom<any>): void { atom._watched = false - if (atom._watchedCleanups?.length) { - atom._watchedCleanups.forEach((cleanup) => cleanup?.()) - atom._watchedCleanups.length = 0 + const cleanups = atom._watchedCleanups + atom._watchedCleanups = [] + let firstError: unknown + if (cleanups?.length) { + for (const cleanup of cleanups) { + try { + cleanup?.() + } catch (error) { + firstError ??= error + } + } } if (atom.depsTail !== undefined) { atom.depsTail = undefined atom.flags = ReactiveFlags.Mutable | ReactiveFlags.Dirty purgeDeps(atom) } + if (firstError) { + throw firstError + } },🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/store/src/atom.ts` around lines 66 - 79, The watched/unwatched lifecycle must be made exception-safe: in watched(InternalAtom) initialize atom._watchedCleanups = [] before running any setup and then iterate atom._watchedSubs (not using map) calling each setup in a try block and pushing its returned cleanup (if any) into atom._watchedCleanups; if a setup throws, ensure atom._watchedCleanups remains set with already-collected cleanup functions and rethrow the error. In unwatched(InternalAtom) iterate atom._watchedCleanups and invoke each cleanup inside its own try/catch so one throwing cleanup does not prevent others from running, then always clear atom._watchedCleanups.length = 0 and set atom._watched = false.packages/store/src/atom.ts lines 259 to 273OutdatedResolvedby justjake(GitHub profile, opens in a new tab)@@ -185,3 +255,19 @@185255 },186256 }187257 },258+259+ whileWatched(listener: WatchedEffect): () => void {260+ atom._watchedSubs ??= []261+ atom._watchedSubs.push(listener)262+ if (atom._watched) {263+ atom._watchedCleanups ??= []264+ atom._watchedCleanups.push(listener())265+ }266+ return () => {267+ if (!atom._watchedSubs) {268+ return269+ }270+ const index = atom._watchedSubs.indexOf(listener)271+ if (index !== -1) {272+ atom._watchedSubs.splice(index, 1)273+ }⚠️ Potential issue | 🟡 Minor
stop()removes the wrong entry for duplicate registrations.If the same function reference is passed to
whileWatched()more than once, both returnedstopclosures useindexOf(listener)and target the first match. Calling the second stopper first removes the earlier registration instead of its own one, so future watch cycles can keep one listener active unexpectedly.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/store/src/atom.ts` around lines 259 - 273, The stop closure removes the first matching listener via indexOf, which breaks when the same listener was registered multiple times; change the registration to capture the cleanup return and have the stopper remove the most recently added matching entries using lastIndexOf: when pushing to atom._watchedSubs, capture the pushed listener (or its index) and when you push the cleanup (listener()) capture that cleanup value into a local (e.g., cleanupRef), then in the returned stop() use atom._watchedSubs.lastIndexOf(listener) to find and splice the correct (most recent) subscriber and use atom._watchedCleanups.lastIndexOf(cleanupRef) to remove the corresponding cleanup entry. Ensure you only attempt to remove when the found index !== -1.View your CI Pipeline Execution ↗ for commit 768b8b558e48c7644d75a97108dadaa9dddc10dc
Command Status Duration Result nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded 44s View ↗ nx run-many --target=build --exclude=examples/**✅ Succeeded <1s View ↗
☁️ Nx Cloud last updated this comment at
2026-04-18 19:27:11UTC@tanstack/angular-store
npm i https://pkg.pr.new/@tanstack/angular-store@312@tanstack/preact-store
npm i https://pkg.pr.new/@tanstack/preact-store@312@tanstack/react-store
npm i https://pkg.pr.new/@tanstack/react-store@312@tanstack/solid-store
npm i https://pkg.pr.new/@tanstack/solid-store@312@tanstack/store
npm i https://pkg.pr.new/@tanstack/store@312@tanstack/svelte-store
npm i https://pkg.pr.new/@tanstack/svelte-store@312@tanstack/vue-store
npm i https://pkg.pr.new/@tanstack/vue-store@312commit:
768b8b5🧹 Nitpick comments (4)
docs/reference/classes/ReadonlyStore.md (2)
136-137: Update terminology to match the documented entity.The description references "atom" but this is
ReadonlyStoredocumentation. Consider updating to "while the store is watched" for clarity.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@docs/reference/classes/ReadonlyStore.md` around lines 136 - 137, The docs mention "atom" in the ReadonlyStore API description; update the wording to refer to the documented entity by changing phrases like "while the atom is watched" and "when the atom is unwatched" to "while the store is watched" and "when the store is unwatched" (refer to ReadonlyStore and the effect callback) so the terminology matches the ReadonlyStore documentation.
136-156: Consider using the more detailed description from BaseAtom docs.The Atom/BaseAtom documentation provides a more precise description that clarifies when the effect runs ("when the first subscriber is added") and includes a helpful example. For consistency and completeness, consider:
- Using the detailed description: "effect will be called when the first subscriber is added. effect may return a cleanup function, which will be called when the store is unwatched."
- Adding the
createTickerexample (adapted for stores if appropriate) - Using consistent terminology ("cleanup function" instead of "stop function")
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@docs/reference/classes/ReadonlyStore.md` around lines 136 - 156, Update the ReadonlyStore docs to match BaseAtom wording: change the effect description to "effect will be called when the first subscriber is added. effect may return a cleanup function, which will be called when the store is unwatched." Replace the "stop function" wording with "cleanup function" everywhere in this doc and ensure the parameter type reference still points to WatchedEffect; additionally add the adapted createTicker example (from BaseAtom) illustrating effect usage for stores and showing returning a cleanup function, and keep the Returns section consistent with the new terminology for the returned cleanup function.docs/reference/classes/Store.md (2)
170-171: Update terminology to match the documented entity.The description references "atom" but this is
Storedocumentation. Consider updating to "while the store is watched" for clarity.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@docs/reference/classes/Store.md` around lines 170 - 171, Summary: The docs use "atom" where they should reference "Store". Update the wording to match the documented entity by changing references from "atom" to "store" in the sentence describing effect. Specifically, in the Store documentation entry that mentions `effect`, replace phrases like "while the atom is watched" and "when the atom is unwatched" with "while the store is watched" and "when the store is unwatched" so the terminology matches the `Store` concept and the `effect` description.
170-189: Consider using the more detailed description from BaseAtom docs.The Atom/BaseAtom documentation provides a more precise description that clarifies when the effect runs ("when the first subscriber is added") and includes a helpful example. For consistency and completeness, consider:
- Using the detailed description: "effect will be called when the first subscriber is added. effect may return a cleanup function, which will be called when the store is unwatched."
- Adding the
createTickerexample (adapted for stores if appropriate) - Using consistent terminology ("cleanup function" instead of "stop function")
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@docs/reference/classes/Store.md` around lines 170 - 189, Update the documentation for the Store watch/effect section to match BaseAtom's more precise wording: say that `effect` (type `WatchedEffect`) "will be called when the first subscriber is added" and that `effect` may return a "cleanup function" which is called when the store is unwatched; replace the ambiguous "stop" wording with "cleanup function" everywhere in this section; also add the adapted `createTicker` example (or a short store-specific example) showing subscription start/cleanup to demonstrate lifecycle semantics. Ensure references to `effect`, `WatchedEffect`, and the example function name (e.g., `createTicker`) are included so reviewers can locate and verify the changes.🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed. Nitpick comments: In `@docs/reference/classes/ReadonlyStore.md`: - Around line 136-137: The docs mention "atom" in the ReadonlyStore API description; update the wording to refer to the documented entity by changing phrases like "while the atom is watched" and "when the atom is unwatched" to "while the store is watched" and "when the store is unwatched" (refer to ReadonlyStore and the effect callback) so the terminology matches the ReadonlyStore documentation. - Around line 136-156: Update the ReadonlyStore docs to match BaseAtom wording: change the effect description to "effect will be called when the first subscriber is added. effect may return a cleanup function, which will be called when the store is unwatched." Replace the "stop function" wording with "cleanup function" everywhere in this doc and ensure the parameter type reference still points to WatchedEffect; additionally add the adapted createTicker example (from BaseAtom) illustrating effect usage for stores and showing returning a cleanup function, and keep the Returns section consistent with the new terminology for the returned cleanup function. In `@docs/reference/classes/Store.md`: - Around line 170-171: Summary: The docs use "atom" where they should reference "Store". Update the wording to match the documented entity by changing references from "atom" to "store" in the sentence describing effect. Specifically, in the Store documentation entry that mentions `effect`, replace phrases like "while the atom is watched" and "when the atom is unwatched" with "while the store is watched" and "when the store is unwatched" so the terminology matches the `Store` concept and the `effect` description. - Around line 170-189: Update the documentation for the Store watch/effect section to match BaseAtom's more precise wording: say that `effect` (type `WatchedEffect`) "will be called when the first subscriber is added" and that `effect` may return a "cleanup function" which is called when the store is unwatched; replace the ambiguous "stop" wording with "cleanup function" everywhere in this section; also add the adapted `createTicker` example (or a short store-specific example) showing subscription start/cleanup to demonstrate lifecycle semantics. Ensure references to `effect`, `WatchedEffect`, and the example function name (e.g., `createTicker`) are included so reviewers can locate and verify the changes.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
2809a279-054d-4237-8a98-2fc756a7f36e📥 Commits
Reviewing files that changed from the base of the PR and between 6dc28fbcf83981a35dd686c7bb56393f4b6e315a and 768b8b558e48c7644d75a97108dadaa9dddc10dc.
📒 Files selected for processing (26)
docs/reference/classes/ReadonlyStore.mddocs/reference/classes/Store.mddocs/reference/functions/batch.mddocs/reference/functions/createAsyncAtom.mddocs/reference/functions/createAtom.mddocs/reference/functions/createExternalStoreAtom.mddocs/reference/functions/createStore.mddocs/reference/functions/flush.mddocs/reference/index.mddocs/reference/interfaces/Atom.mddocs/reference/interfaces/AtomOptions.mddocs/reference/interfaces/BaseAtom.mddocs/reference/interfaces/InternalBaseAtom.mddocs/reference/interfaces/InternalReadonlyAtom.mddocs/reference/interfaces/InteropSubscribable.mddocs/reference/interfaces/Readable.mddocs/reference/interfaces/ReadonlyAtom.mddocs/reference/interfaces/Subscribable.mddocs/reference/interfaces/Subscription.mddocs/reference/type-aliases/AnyAtom.mddocs/reference/type-aliases/Observer.mddocs/reference/type-aliases/Selection.mddocs/reference/type-aliases/StoreAction.mddocs/reference/type-aliases/StoreActionMap.mddocs/reference/type-aliases/StoreActionsFactory.mddocs/reference/type-aliases/WatchedEffect.md
✅ Files skipped from review due to trivial changes (21)
- docs/reference/type-aliases/Selection.md
- docs/reference/functions/batch.md
- docs/reference/type-aliases/StoreActionMap.md
- docs/reference/type-aliases/StoreAction.md
- docs/reference/interfaces/AtomOptions.md
- docs/reference/type-aliases/StoreActionsFactory.md
- docs/reference/interfaces/Subscription.md
- docs/reference/interfaces/InteropSubscribable.md
- docs/reference/functions/createAtom.md
- docs/reference/type-aliases/WatchedEffect.md
- docs/reference/interfaces/InternalBaseAtom.md
- docs/reference/type-aliases/Observer.md
- docs/reference/interfaces/InternalReadonlyAtom.md
- docs/reference/index.md
- docs/reference/functions/createExternalStoreAtom.md
- docs/reference/functions/createStore.md
- docs/reference/interfaces/Subscribable.md
- docs/reference/functions/flush.md
- docs/reference/functions/createAsyncAtom.md
- docs/reference/type-aliases/AnyAtom.md
- docs/reference/interfaces/Readable.md
Actionable comments posted: 2
🧹 Nitpick comments (2)
packages/store/src/atom.ts (2)
156-160: Orphaned JSDoc comment.This documentation block doesn't precede any function or declaration. It may be leftover from refactoring and should be removed or relocated to the appropriate function.
♻️ Proposed fix
-/** - * Called when the atom is watched. - * Returns a cleanup function that will be called when the atom is unwatched. - */ - interface InternalAtom<T> extends ReactiveNode {🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/store/src/atom.ts` around lines 156 - 160, Remove the orphaned JSDoc block (the comment describing "Called when the atom is watched. Returns a cleanup function...") or move it immediately above the actual function that handles watching/unwatching the atom (search for functions named watch, onWatch, subscribe, or unwatch in this module, e.g., the atom's watch/unwatch handler). Ensure the JSDoc is directly adjacent to the function/declaration it documents and delete the standalone comment if no matching function exists.
175-178: Remove dead properties_watched,_watchedSubs, and_watchedCleanupsfromInternalAtominterface.These properties are declared at lines 175-177 but never used. The watch mechanism was refactored to use
WatchableNode's_watches,_watchEffects, and_watchCleanupsvia the module-levelwhileWatched()function, making these vestiges unnecessary.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/store/src/atom.ts` around lines 175 - 178, Remove the dead properties from the InternalAtom interface: delete the _watched, _watchedSubs, and _watchedCleanups declarations from InternalAtom; the watch logic now uses WatchableNode's _watches, _watchEffects, and _watchCleanups via whileWatched(), so update InternalAtom by removing these unused fields to avoid dead API surface and unused type members.🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed. Inline comments: In `@packages/store/src/atom.ts`: - Around line 94-98: The cleanup loop over the cleanups array can stop early if a cleanup function throws; update the loop in the atom teardown (the block iterating cleanups[]) to wrap each invocation in a try/catch so every cleanup is attempted even when one throws. Inside the catch, either log the error (e.g., console.error or a logger) and continue, or collect errors into an array and rethrow a single AggregateError after the loop so callers are aware of failures while ensuring all cleanup functions run. Ensure you reference the same cleanups[] invocation and preserve the optional call pattern (cleanups[i]?.()) while adding per-iteration try/catch and error handling. - Around line 68-78: The loop that runs node._watchEffects should guard each invocation so one throwing effect doesn't stop subsequent effects or leave a mismatched node._watchCleanups array; modify the block around node._watchEffects/cleanups so each ef() call is wrapped in try-catch, always assign a slot in node._watchCleanups (leaving undefined if ef throws), collect any thrown errors into an array, continue invoking remaining effects, and after the loop rethrow a combined error (or the first error) if any were captured. --- Nitpick comments: In `@packages/store/src/atom.ts`: - Around line 156-160: Remove the orphaned JSDoc block (the comment describing "Called when the atom is watched. Returns a cleanup function...") or move it immediately above the actual function that handles watching/unwatching the atom (search for functions named watch, onWatch, subscribe, or unwatch in this module, e.g., the atom's watch/unwatch handler). Ensure the JSDoc is directly adjacent to the function/declaration it documents and delete the standalone comment if no matching function exists. - Around line 175-178: Remove the dead properties from the InternalAtom interface: delete the _watched, _watchedSubs, and _watchedCleanups declarations from InternalAtom; the watch logic now uses WatchableNode's _watches, _watchEffects, and _watchCleanups via whileWatched(), so update InternalAtom by removing these unused fields to avoid dead API surface and unused type members.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
2fed461e-0bda-4356-a150-2f49f4be52bf📥 Commits
Reviewing files that changed from the base of the PR and between 768b8b558e48c7644d75a97108dadaa9dddc10dc and bf088729b124da7c25af0136dc6b76e5a1d6d28e.
📒 Files selected for processing (3)
packages/store/src/atom.tspackages/store/tests/external-store-atom.test.tspackages/store/tests/while-watched.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/store/tests/external-store-atom.test.ts
@@ -28,0 +58,21 @@58+ addWatch(deps.dep)59+ deps = deps.nextDep60+ }61+62+ // 2. start/run own watch effects.63+ // Assign `_watchCleanups` BEFORE invoking any effect and seed it with64+ // packed `undefined` slots (avoid `new Array(len)` which gives a holey65+ // SMI array in V8). A re-entrant `whileWatched()` during `ef()` pushes66+ // into this same array at `i >= len`, keeping indices aligned with67+ // `_watchEffects`; the outer loop writes the pre-reserved slot by index.68+ const watchEffects = node._watchEffects69+ if (watchEffects?.length) {70+ const len = watchEffects.length71+ const cleanups: Array<(() => void) | void | undefined> = []72+ node._watchCleanups = cleanups73+ for (let i = 0; i < len; i++) cleanups.push(undefined)74+ for (let i = 0; i < len; i++) {75+ const ef = watchEffects[i]76+ if (ef) cleanups[i] = ef()77+ }78+ }⚠️ Potential issue | 🟡 Minor
Exception handling gap in watch effect initialization.
If an effect at index
ithrows, subsequent effects won't run and their cleanups won't be registered. While this may be acceptable for simple cases, it could leave the system in an inconsistent state where some effects ran but others didn't.Consider wrapping each effect invocation in a try-catch to ensure all effects get a chance to run, collecting errors to rethrow after.
🛡️ Suggested hardening
if (watchEffects?.length) { const len = watchEffects.length const cleanups: Array<(() => void) | void | undefined> = [] node._watchCleanups = cleanups for (let i = 0; i < len; i++) cleanups.push(undefined) + let firstError: unknown for (let i = 0; i < len; i++) { const ef = watchEffects[i] - if (ef) cleanups[i] = ef() + if (ef) { + try { + cleanups[i] = ef() + } catch (e) { + firstError ??= e + } + } } + if (firstError) throw firstError }📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change67- // `_watchEffects`; the outer loop writes the pre-reserved slot by index.68- const watchEffects = node._watchEffects69- if (watchEffects?.length) {70- const len = watchEffects.length71- const cleanups: Array<(() => void) | void | undefined> = []72- node._watchCleanups = cleanups73- for (let i = 0; i < len; i++) cleanups.push(undefined)74- for (let i = 0; i < len; i++) {75- const ef = watchEffects[i]76- if (ef) cleanups[i] = ef()77- }67+ const watchEffects = node._watchEffects68+ if (watchEffects?.length) {69+ const len = watchEffects.length70+ const cleanups: Array<(() => void) | void | undefined> = []71+ node._watchCleanups = cleanups72+ for (let i = 0; i < len; i++) cleanups.push(undefined)73+ let firstError: unknown74+ for (let i = 0; i < len; i++) {75+ const ef = watchEffects[i]76+ if (ef) {77+ try {78+ cleanups[i] = ef()79+ } catch (e) {80+ firstError ??= e81+ }82+ }83+ }84+ if (firstError) throw firstError85+ }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/store/src/atom.ts` around lines 68 - 78, The loop that runs node._watchEffects should guard each invocation so one throwing effect doesn't stop subsequent effects or leave a mismatched node._watchCleanups array; modify the block around node._watchEffects/cleanups so each ef() call is wrapped in try-catch, always assign a slot in node._watchCleanups (leaving undefined if ef throws), collect any thrown errors into an array, continue invoking remaining effects, and after the loop rethrow a combined error (or the first error) if any were captured.@@ -28,0 +78,21 @@78+ }79+ }80+}81+82+function removeWatch(node: WatchableNode) {83+ node._watches ??= 084+ const next = --node._watches85+86+ // On last unwatch, node becomes dead:87+ if (next === 0) {88+ // 1. Clean up effects.89+ // Snapshot and clear `_watchCleanups` BEFORE invoking any cleanup, so a90+ // re-entrant subscribe during cleanup sees a consistent (empty) state and91+ // can rebuild cleanups into a fresh array via addWatch.92+ const cleanups = node._watchCleanups93+ node._watchCleanups = undefined94+ if (cleanups) {95+ for (let i = cleanups.length - 1; i >= 0; i--) {96+ cleanups[i]?.()97+ }98+ }⚠️ Potential issue | 🟡 Minor
Cleanup loop could swallow errors from later teardowns.
If a cleanup function throws, the for-loop exits immediately and remaining cleanups won't run. This could leave external resources (like subscriptions) active.
🛡️ Suggested hardening
const cleanups = node._watchCleanups node._watchCleanups = undefined if (cleanups) { + let firstError: unknown for (let i = cleanups.length - 1; i >= 0; i--) { - cleanups[i]?.() + try { + cleanups[i]?.() + } catch (e) { + firstError ??= e + } } + if (firstError) throw firstError }📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change93- node._watchCleanups = undefined94- if (cleanups) {95- for (let i = cleanups.length - 1; i >= 0; i--) {96- cleanups[i]?.()97- }93+ const cleanups = node._watchCleanups94+ node._watchCleanups = undefined95+ if (cleanups) {96+ let firstError: unknown97+ for (let i = cleanups.length - 1; i >= 0; i--) {98+ try {99+ cleanups[i]?.()100+ } catch (e) {101+ firstError ??= e102+ }103+ }104+ if (firstError) throw firstError105+ }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/store/src/atom.ts` around lines 94 - 98, The cleanup loop over the cleanups array can stop early if a cleanup function throws; update the loop in the atom teardown (the block iterating cleanups[]) to wrap each invocation in a try/catch so every cleanup is attempted even when one throws. Inside the catch, either log the error (e.g., console.error or a logger) and continue, or collect errors into an array and rethrow a single AggregateError after the loop so callers are aware of failures while ensuring all cleanup functions run. Ensure you reference the same cleanups[] invocation and preserve the optional call pattern (cleanups[i]?.()) while adding per-iteration try/catch and error handling.@davidkpiano this is ready for review
- @@ -0,0 +312,21 @@312+313+ // _watches must not be stuck: a fresh subscribe re-activates.314+ const sub2 = atom.subscribe(() => {})315+ expect(activate).toHaveBeenCalledTimes(3)316+ expect(ext.listenerCount()).toBe(1)317+ sub2.unsubscribe()318+ expect(ext.listenerCount()).toBe(0)319+ })320+321+ test('adding a whileWatched during another effect runs it immediately', () => {322+ const atom = createAtom(0)323+ const lateEffect = vi.fn()324+ const lateCleanup = vi.fn()325+326+ atom.whileWatched(() => {327+ atom.whileWatched(() => {328+ lateEffect()329+ return lateCleanup330+ })331+ })332+
Nit: make sure it's been called 0 times before
davidkpiano(GitHub profile, opens in a new tab) approved these changes
can has merge?
Sign in to join this conversation.
Note
Reviews paused#
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
📝 Walkthrough
Walkthrough#
This pull request introduces a watch liveness mechanism to the TanStack store family, adding three new APIs:
atom.whileWatched(cb)andstore.whileWatched(cb)for registering effects that run when subscribers become active, andcreateExternalStoreAtomfor syncing external state into atoms. Implementation spans core store package with comprehensive tests.Changes#
.changeset/ninety-actors-hide.md,docs/config.jsonWatchedEffecttype andcreateExternalStoreAtomfunction.packages/store/src/atom.tsWatchedEffecttype,whileWatched()method on atoms, andcreateExternalStoreAtom()function. Adds internal state (_watched,_watchedSubs,_watchedCleanups) and modifies link/unlink behavior to propagate liveness between watched nodes and dependencies.packages/store/src/store.ts,packages/store/src/types.tsStore,ReadonlyStore, andBaseAtomwithwhileWatched()method that delegates to the atom implementation.packages/store/src/signal.tswatched()handler with unimplemented stub for signal-based reactivity.packages/store/tests/while-watched.test.ts,packages/store/tests/external-store-atom.test.tsSequence Diagram(s)#
Estimated code review effort#
🎯 4 (Complex) | ⏱️ ~45 minutes
Poem#
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands and usage tips.