Skip to content
Source
Sign inSign up
TanStack/store

feat(core) atom.whileWatched (useEffect-like primitive) and createExternalStoreAtom #312

Openjustjake(GitHub profile, opens in a new tab)wants to merge 23 commits intomain fromrefs/pull/312/headopened

🎯 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 createExternalStoreAtom to synchronize external store state with atoms automatically.
  • Documentation

    • Updated API reference navigation with entries for new functionality.
    1. justjake(GitHub profile, opens in a new tab) changed the title

    2. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      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_commits setting.

      Use the following commands to manage reviews:

      • @coderabbitai resume to resume automatic reviews.
      • @coderabbitai review to trigger a single review.

      Use the checkboxes below for quick actions:

      • ▶️ Resume reviews
      • 🔍 Trigger review
      📝 Walkthrough

      Walkthrough

      This pull request introduces a watch liveness mechanism to the TanStack store family, adding three new APIs: atom.whileWatched(cb) and store.whileWatched(cb) for registering effects that run when subscribers become active, and createExternalStoreAtom for syncing external state into atoms. Implementation spans core store package with comprehensive tests.

      Changes

      Cohort / File(s)Summary
      Changeset & Documentation
      .changeset/ninety-actors-hide.md, docs/config.json
      Declares minor version bumps for all store packages and adds API reference entries for WatchedEffect type and createExternalStoreAtom function.
      Atom Core Implementation
      packages/store/src/atom.ts
      Introduces watch liveness tracking with WatchedEffect type, whileWatched() method on atoms, and createExternalStoreAtom() function. Adds internal state (_watched, _watchedSubs, _watchedCleanups) and modifies link/unlink behavior to propagate liveness between watched nodes and dependencies.
      Store & Type Definitions
      packages/store/src/store.ts, packages/store/src/types.ts
      Extends Store, ReadonlyStore, and BaseAtom with whileWatched() method that delegates to the atom implementation.
      Signal Configuration
      packages/store/src/signal.ts
      Adds placeholder watched() handler with unimplemented stub for signal-based reactivity.
      Test Suite
      packages/store/tests/while-watched.test.ts, packages/store/tests/external-store-atom.test.ts
      Comprehensive test coverage for watch liveness lifecycle (activation, cleanup, ref-counting, nested dependencies), external store integration, and subscription management across multiple concurrent handlers.

      Sequence Diagram(s)

      sequenceDiagram
          participant ExtStore as External Store
          participant Atom as Atom Instance
          participant Sub as Subscriber
          participant Effect as WatchedEffect
          
          Sub->>Atom: subscribe()
          Note over Atom: _watches count: 0→1 (becomes "live")
          activate Effect
          Atom->>Effect: execute whileWatched callback
          Effect-->>Atom: return cleanup function
          deactivate Effect
          
          ExtStore->>Atom: external state changes
          Atom->>Sub: notify of change
          Sub->>Atom: get() updated snapshot
          
          Sub->>Atom: unsubscribe()
          Note over Atom: _watches count: 1→0 (becomes "dead")
          activate Effect
          Atom->>Effect: execute cleanup function
          deactivate Effect
      sequenceDiagram
          participant ExtStore as External Store
          participant CreateExt as createExternalStoreAtom()
          participant TriggerAtom as Trigger Atom
          participant MainAtom as Atom (returned)
          participant Consumer as Consumer/Subscriber
          
          Consumer->>MainAtom: subscribe()
          MainAtom->>TriggerAtom: whileWatched effect starts
          TriggerAtom->>CreateExt: subscribe to ExtStore
          activate CreateExt
          CreateExt->>ExtStore: call subscribe(onStoreChange)
          deactivate CreateExt
          
          ExtStore->>CreateExt: onStoreChange() callback
          CreateExt->>TriggerAtom: invalidate()
          TriggerAtom->>MainAtom: notify subscribers
          MainAtom->>Consumer: propagate getSnapshot()
          
          Consumer->>MainAtom: unsubscribe()
          MainAtom->>TriggerAtom: whileWatched cleanup executes
          CreateExt->>ExtStore: call unsubscribe (cleanup)

      Estimated code review effort

      🎯 4 (Complex) | ⏱️ ~45 minutes

      Poem

      🐰 Behold, the atoms now whileWatched with care, Effects that bloom when eyes are aware, External stores sync through clever atomic dance, Liveness flows free in this reactive trance! 🌟

      🚥 Pre-merge checks | ✅ 4 | ❌ 1

      ❌ Failed checks (1 warning)

      Check nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring coverage is 20.00% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
      ✅ Passed checks (4 passed)
      Check nameStatusExplanation
      Title check✅ PassedThe title accurately and concisely summarizes the main changes: introducing atom.whileWatched as a useEffect-like primitive and createExternalStoreAtom functionality.
      Description check✅ PassedThe description includes all required template sections with comprehensive details about changes, test completion, and changeset generation.
      Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
      Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.
      ✏️ Tip: You can configure your own custom pre-merge checks in the settings.
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests

      Comment `@coderabbitai help` to get the list of available commands and usage tips.
    3. Actionable comments posted: 7

      🧹 Nitpick comments (1)
      packages/store/tests/while-watched.test.ts (1)

      103-124: Add a stop()-while-watched test case.

      Current stop() tests cover idempotency and future activations, but not cancellation during an active watch. Add a case where stop() 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.md
      • docs/config.json
      • docs/reference/functions/createExternalStoreAtom.md
      • docs/reference/type-aliases/WatchedEffect.md
      • packages/store/src/alien.ts
      • packages/store/src/atom.ts
      • packages/store/src/signal.ts
      • packages/store/src/store.ts
      • packages/store/src/types.ts
      • packages/store/tests/external-store-atom.test.ts
      • packages/store/tests/while-watched.test.ts
      @@ -0,0 +1,10 @@
      1+---
      2+id: WatchedEffect
      3+title: WatchedEffect
      4+---
      5+
      6+# Type Alias: WatchedEffect()
      7+
      8+```ts
      9+type WatchedEffect = () => () => void | void | undefined;
      10+```
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      ⚠️ 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.
    4. Actionable comments posted: 1

      ♻️ Duplicate comments (1)
      packages/store/src/atom.ts (1)

      258-273: ⚠️ Potential issue | 🟠 Major

      Stopping an active whileWatched listener still leaves its cleanup running.

      When stop() is called after Line 263 has registered a cleanup, Lines 269-271 remove the listener from _watchedSubs but never remove or invoke the matching entry in _watchedCleanups. The external resource stays live until full unwatched(), 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.ts
      • packages/store/src/types.ts
      🚧 Files skipped from review as they are similar to previous changes (1)
      • packages/store/src/types.ts
    5. Actionable comments posted: 2

      ♻️ Duplicate comments (1)
      packages/store/src/atom.ts (1)

      196-203: ⚠️ Potential issue | 🟠 Major

      Avoid subscribing the external store on plain get().

      Line 202 still creates the trigger -> atom dependency during computed evaluation. A one-off atom.get() can therefore mark trigger as watched and keep subscribe(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 that stop() only affects future watch cycles.

      “Returns a stop function 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
    6. nx-cloud[bot](GitHub profile, opens in a new tab)commented

      View your CI Pipeline Execution ↗ for commit 768b8b558e48c7644d75a97108dadaa9dddc10dc

      CommandStatusDurationResult
      nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded44sView ↗
      nx run-many --target=build --exclude=examples/**✅ Succeeded<1sView ↗

      ☁️ Nx Cloud last updated this comment at 2026-04-18 19:27:11 UTC

    7. pkg-pr-new[bot](GitHub profile, opens in a new tab)commented
      @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@312

      commit: 768b8b5

    8. 🧹 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 ReadonlyStore documentation. 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:

      1. 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."
      2. Adding the createTicker example (adapted for stores if appropriate)
      3. 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 Store documentation. 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:

      1. 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."
      2. Adding the createTicker example (adapted for stores if appropriate)
      3. 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.md
      • docs/reference/classes/Store.md
      • docs/reference/functions/batch.md
      • docs/reference/functions/createAsyncAtom.md
      • docs/reference/functions/createAtom.md
      • docs/reference/functions/createExternalStoreAtom.md
      • docs/reference/functions/createStore.md
      • docs/reference/functions/flush.md
      • docs/reference/index.md
      • docs/reference/interfaces/Atom.md
      • docs/reference/interfaces/AtomOptions.md
      • docs/reference/interfaces/BaseAtom.md
      • docs/reference/interfaces/InternalBaseAtom.md
      • docs/reference/interfaces/InternalReadonlyAtom.md
      • docs/reference/interfaces/InteropSubscribable.md
      • docs/reference/interfaces/Readable.md
      • docs/reference/interfaces/ReadonlyAtom.md
      • docs/reference/interfaces/Subscribable.md
      • docs/reference/interfaces/Subscription.md
      • docs/reference/type-aliases/AnyAtom.md
      • docs/reference/type-aliases/Observer.md
      • docs/reference/type-aliases/Selection.md
      • docs/reference/type-aliases/StoreAction.md
      • docs/reference/type-aliases/StoreActionMap.md
      • docs/reference/type-aliases/StoreActionsFactory.md
      • docs/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
    9. 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 _watchedCleanups from InternalAtom interface.

      These properties are declared at lines 175-177 but never used. The watch mechanism was refactored to use WatchableNode's _watches, _watchEffects, and _watchCleanups via the module-level whileWatched() 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.ts
      • packages/store/tests/external-store-atom.test.ts
      • packages/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.nextDep
      60+ }
      61+
      62+ // 2. start/run own watch effects.
      63+ // Assign `_watchCleanups` BEFORE invoking any effect and seed it with
      64+ // packed `undefined` slots (avoid `new Array(len)` which gives a holey
      65+ // SMI array in V8). A re-entrant `whileWatched()` during `ef()` pushes
      66+ // into this same array at `i >= len`, keeping indices aligned with
      67+ // `_watchEffects`; the outer loop writes the pre-reserved slot by index.
      68+ const watchEffects = node._watchEffects
      69+ if (watchEffects?.length) {
      70+ const len = watchEffects.length
      71+ const cleanups: Array<(() => void) | void | undefined> = []
      72+ node._watchCleanups = cleanups
      73+ 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+ }
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      ⚠️ Potential issue | 🟡 Minor

      Exception handling gap in watch effect initialization.

      If an effect at index i throws, 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 change
      67- // `_watchEffects`; the outer loop writes the pre-reserved slot by index.
      68- const watchEffects = node._watchEffects
      69- if (watchEffects?.length) {
      70- const len = watchEffects.length
      71- const cleanups: Array<(() => void) | void | undefined> = []
      72- node._watchCleanups = cleanups
      73- 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._watchEffects
      68+ if (watchEffects?.length) {
      69+ const len = watchEffects.length
      70+ const cleanups: Array<(() => void) | void | undefined> = []
      71+ node._watchCleanups = cleanups
      72+ for (let i = 0; i < len; i++) cleanups.push(undefined)
      73+ let firstError: unknown
      74+ 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 ??= e
      81+ }
      82+ }
      83+ }
      84+ if (firstError) throw firstError
      85+ }
      🤖 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 ??= 0
      84+ const next = --node._watches
      85+
      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 a
      90+ // re-entrant subscribe during cleanup sees a consistent (empty) state and
      91+ // can rebuild cleanups into a fresh array via addWatch.
      92+ const cleanups = node._watchCleanups
      93+ node._watchCleanups = undefined
      94+ if (cleanups) {
      95+ for (let i = cleanups.length - 1; i >= 0; i--) {
      96+ cleanups[i]?.()
      97+ }
      98+ }
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      ⚠️ 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 change
      93- node._watchCleanups = undefined
      94- if (cleanups) {
      95- for (let i = cleanups.length - 1; i >= 0; i--) {
      96- cleanups[i]?.()
      97- }
      93+ const cleanups = node._watchCleanups
      94+ node._watchCleanups = undefined
      95+ if (cleanups) {
      96+ let firstError: unknown
      97+ for (let i = cleanups.length - 1; i >= 0; i--) {
      98+ try {
      99+ cleanups[i]?.()
      100+ } catch (e) {
      101+ firstError ??= e
      102+ }
      103+ }
      104+ if (firstError) throw firstError
      105+ }
      🤖 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.
    10. @davidkpiano this is ready for review

    11. @@ -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 lateCleanup
      330+ })
      331+ })
      332+

      Nit: make sure it's been called 0 times before

    12. davidkpiano(GitHub profile, opens in a new tab) approved these changes

Sign in to join this conversation.