diff --git a/AGENTS.md b/AGENTS.md index cb453bc..7bffba2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,6 +14,18 @@ when they need to. to keep old call sites working. Remove or change the old API outright. - Don't hold back a fix or a refactor, or split it into a "safe" version, because it would break callers. +- Never choose a design for the release type it gets. When a problem has a + clean fix that breaks callers and a weaker one that ships as a patch, + take the clean fix and release it as a major version. The release type + follows from the design, never the other way round. +- When a problem has more than one fix, compare them on their merits and + take the cleanest, even when another keeps every caller working. Name the + options you rejected in the pull request, and say why. + + Example: a first version of #291 kept `useObserve`'s subscription during + render and released it with a 10 s timer, so that it could ship as a + patch. The clean fix subscribes only after commit. It changes what the + first render shows, so it ships as a major version. - Judge a design on its merits for the general use case. Don't argue for or against it from how one app (oboku, for example) uses the library, and don't shape it around that app's code. diff --git a/gitbook/reactjrx/bindings/react/useobserve.md b/gitbook/reactjrx/bindings/react/useobserve.md index 5b94f9c..245b441 100644 --- a/gitbook/reactjrx/bindings/react/useobserve.md +++ b/gitbook/reactjrx/bindings/react/useobserve.md @@ -1,6 +1,6 @@ # useObserve -The `useObserve` hook subscribes to an observable and returns its latest value, along with the state of the stream. It is the building block of higher order hooks such as the ones used in [Queries](https://app.gitbook.com/s/uE1Z7PHuhXh0NunQ33Mr/queries "mention"). +The `useObserve` hook subscribes to an observable once the component has mounted, and returns its latest value, along with whether it has one and the state of the stream. ```typescript useObserve(source, optionsOrDeps?, deps?) @@ -10,9 +10,12 @@ useObserve(source, optionsOrDeps?, deps?) ```typescript function App () { - const { data: user } = useObserve(user$) + const { data: user, status } = useObserve(user$) - return
current user: { user?.name }
+ if (status === "error") return + if (status === "pending") return + + return
current user: { user.name }
} ``` @@ -23,12 +26,10 @@ function useObserve( source: Observable | (() => Observable | undefined) | undefined, optionsOrDeps?: Options | DependencyList, deps?: DependencyList -): { - data: T | DefaultValue - status: "pending" | "success" | "error" - observableState: "live" | "complete" | "error" - error: unknown -} +): + | { status: "pending"; data: DefaultValue; error: undefined; observableState: "live" | "complete" } + | { status: "success"; data: T; error: undefined; observableState: "live" | "complete" } + | { status: "error"; data: T | DefaultValue; error: unknown; observableState: "error" } ``` ```typescript @@ -42,7 +43,7 @@ interface Options { * `source`: An observable, a function returning one, or `undefined`. Pass a stable observable directly: the hook subscribes to it again when its reference changes. Otherwise pass a function with `deps`, so the observable is only created again when a dependency changes. With `undefined`, nothing is observed and the default value is returned. * **optional** `options`: - * `defaultValue`: returned until the source emits its first value. A `BehaviorSubject`, or any source that emits synchronously when subscribed, doesn't need it: its value is there on the first render. + * `defaultValue`: returned as `data` while the source has no value. A `BehaviorSubject`, or a signal, has its value on the first render and doesn't need it. Keep it stable: a new object on every render is a new `data` on every render. * `compareFn`: tells whether a new value equals the previous one. An equal value doesn't re-render. Defaults to strict equality (`===`). Pass [isShallowEqual](../../utils/javascript/isshallowequal.md) (exported by reactjrx) to compare own enumerable properties one level deep, or your own function for a different equality rule. `isShallowEqual` does not compare the contents of `Date`, `Map` or `Set` objects. * **optional** `deps`: The values the function depends on. When one of them changes (compared with [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is)), the function is called again and its observable replaces the previous one. @@ -50,23 +51,29 @@ interface Options { An object with: -* `data`: the latest value. Before the first emission, it's the `BehaviorSubject`'s value or `defaultValue` (`undefined` otherwise). -* `status`: `"pending"` while the source is live, `"success"` once it completes, `"error"` once it errors. -* `observableState`: `"live"`, `"complete"` or `"error"`. +* `status`: whether the source has a value, as the queries of TanStack Query report theirs. + * `"pending"`: the source has no value: none yet, it completed without one, or there is no source. `data` is `defaultValue` (`undefined` otherwise). A source that completes without a value stays `"pending"`, with `observableState: "complete"`. + * `"success"`: the source has a value. `data` is its latest value, typed as one. + * `"error"`: the source errored. `data` keeps its last value, or `defaultValue` if it had none. A `BehaviorSubject` that already errored, or is closed, has no value: `data` is `undefined`, although it is typed as a value. +* `data`: the latest value, or `defaultValue`. Its type follows `status`. +* `observableState`: the life of the stream: `"live"` while it can still emit, `"complete"` once it completed (or without a source), `"error"` once it errored. * `error`: the error the source failed with, when `status` is `"error"`. ### **Caveats** -* The hook subscribes while rendering, so a source that emits synchronously (`of(x)`, a `BehaviorSubject`, a `ReplaySubject` holding a value) has its value on the first render. A source that emits later returns the default value until it does. +* The hook subscribes in an effect, after React commits the render, never during render. A render that React throws away (a Suspense boundary that suspends, an error boundary, an abandoned transition) and a server render subscribe to nothing. +* On the first render, and after a deps change, only a source that holds a value has it: a `BehaviorSubject`, or a signal. Any other source is `"pending"`. +* A source that emits as soon as it is subscribed (`of(x)`, a piped signal, a `ReplaySubject` holding a value) has its value right after mount, in a second render. The first render, still `"pending"`, can reach the screen. A source that emits later stays `"pending"` until it does. To show part of a signal on the first render, in one render, use `useSignalValue(signal, selector)`. +* An observable created during render, such as `source$.pipe(...)` written in the component, is a new observable on every render. Once the component renders again, React throws "Too many re-renders". Create it in a function with `deps`. * A new value that `compareFn` considers equal to the previous one doesn't re-render. By default that's strict equality, so a new object with the same content does re-render. -* An error doesn't throw: the hook returns `status: "error"` with the `error`, keeps the last `data`, and doesn't report the error as unhandled. -* Once the source has completed or errored, the hook doesn't subscribe to it again. Pass a new source, or change `deps`, to start over. +* An error doesn't throw: the hook returns `status: "error"` with the `error`, keeps the last `data`, and doesn't report the error as unhandled. A `compareFn` that throws errors the source the same way. +* When React runs the effects again (`StrictMode` in development, an `` shown again), the hook subscribes again to a live source: a cold one starts over, and values emitted while hidden are missed. A source that completed or errored is not subscribed again. A Suspense boundary that suspends again keeps the subscription. Pass a new source, or change `deps`, to start over. ## Usages #### Displaying a timer -Here we display an infinite timer which starts at `0`. The timer can't emit on the first render, so `defaultValue` provides a value until it does. The `map` makes `1` the first value the source emits. +Here we display an infinite timer which starts at `0`. The timer emits later, so `defaultValue` provides a value until it does. The `map` makes `1` the first value the source emits. ```typescript function App () { @@ -82,7 +89,7 @@ function App () { #### Subscribing to an external subject -A `BehaviorSubject` always holds a value, so it's there on the first render. +A `BehaviorSubject` always holds a value, so it's there on the first render, and `status` is `"success"`. ```typescript const clickedSubject = new BehaviorSubject(0) @@ -99,15 +106,15 @@ function App () { } ``` -Any source that emits synchronously when subscribed, such as a `ReplaySubject` that already holds a value, is there on the first render too. Its type doesn't say so, though, so handle `undefined` or pass a `defaultValue`: +Any other source is `"pending"` on the first render. One that already holds a value, such as a `ReplaySubject`, has it right after mount. Check `status`, and `data` is typed as a value: ```typescript const clickedSubject = new ReplaySubject(1) function App () { - const { data: clicked } = useObserve(clickedSubject) + const { data: clicked, status } = useObserve(clickedSubject) - if (clicked === undefined) return null + if (status !== "success") return null return (
@@ -120,7 +127,7 @@ function App () { #### Selecting part of a value -There is no selector option: map the source to the part you need, and skip values whose selected part didn't change with `distinctUntilChanged`. +There is no selector option: map the source to the part you need, and skip values whose selected part didn't change with `distinctUntilChanged`. For a signal, `useSignalValue(signal, selector)` reads the selected part on the first render instead. ```typescript const value$ = new BehaviorSubject({ foo: "bar", bar: "foo" }) diff --git a/gitbook/reactjrx/important-considerations.md b/gitbook/reactjrx/important-considerations.md index 9694dcc..6c5612a 100644 --- a/gitbook/reactjrx/important-considerations.md +++ b/gitbook/reactjrx/important-considerations.md @@ -6,21 +6,36 @@ description: Because nothing is perfect! ## First render of an observable -`useObserve` subscribes to its source while rendering. A source that emits synchronously when subscribed, such as `of(1)`, a `BehaviorSubject` or a `ReplaySubject` holding a value, therefore has its value on the very first render. +`useObserve` subscribes once React has committed the render, never while rendering. On the first render, and after a deps change, only a source that holds a value has it: a `BehaviorSubject`, or a signal. Any other source returns `status: "pending"` and its default value. -A source that emits later, such as a timer or a request, has no value on the first render: +A source that emits as soon as it is subscribed, such as `of(1)`, a piped signal or a `ReplaySubject` holding a value, has its value right after mount, in a second render. A source that emits later, such as a timer or a request, stays pending until it does: ```typescript const value$ = timer(10) const MyComponent = () => { - const { data } = useObserve(value$) + const { data, status } = useObserve(value$) - // data is undefined on the first render, then 0 once the timer fires + // status is "pending" and data is undefined on the first render, + // then "success" and 0 once the timer fires } ``` -This is expected, and there are two ways to handle it. +This is expected, and there are three ways to handle it. + +### Check `status` + +Render something else until the source has a value. Once `status` is `"success"`, `data` is typed as a value. + +```typescript +const MyComponent = () => { + const { data, status } = useObserve(value$) + + if (status !== "success") return + + return
{data}
+} +``` ### Handle `undefined` @@ -40,7 +55,7 @@ const MyComponent = () => { ### Pass a default value -If you know a sensible value before the source emits, pass it as `defaultValue`. The hook returns it until the first emission. +If you know a sensible value before the source emits, pass it as `defaultValue`. The hook returns it while the source is pending. ```typescript const MyComponent = () => { diff --git a/gitbook/reactjrx/state-signal/about.md b/gitbook/reactjrx/state-signal/about.md index 52444b8..bf4bbd7 100644 --- a/gitbook/reactjrx/state-signal/about.md +++ b/gitbook/reactjrx/state-signal/about.md @@ -84,6 +84,8 @@ const App = () => { }; ``` +Persistence starts once the component has mounted. A render that never commits, and a server render, read and write nothing, and `isHydrated` stays `false` until the stored values are read. + When the shape of a persisted value changes, raise its entry's `version`. A value stored with an older version is discarded, unless the entry has a `hydrate` function. `hydrate` receives every stored value, older versions included, with the version it was stored with. It returns the signal's value: the stored one, a migration of it, or the signal's default, such as `settings.config.default` for the signal below, for a version it does not migrate. A value it migrates from an older version is saved again with the new version. `value` is typed `unknown`, since the storage can hold any shape: narrow it, or cast it for a version your app wrote. In reactjrx 4, `hydrate` received the entry's version, never saw an older value, and had `value` typed as the signal's value: a `hydrate` written for it now checks `version` before it reads `value`. diff --git a/src/lib/binding/useObserve/store.ts b/src/lib/binding/useObserve/store.ts deleted file mode 100644 index 9eb91cd..0000000 --- a/src/lib/binding/useObserve/store.ts +++ /dev/null @@ -1,125 +0,0 @@ -import { - BehaviorSubject, - distinctUntilChanged, - NEVER, - type Observable, - Subscription, - share, - tap, -} from "rxjs" - -export type State = { - data: T | DefaultValue - status: "pending" | "success" | "error" - observableState: "complete" | "error" | "live" - error: Error | undefined -} - -export interface ObservableStoreOptions { - defaultValue: DefaultValue - compareFn: ((a: T, b: T) => boolean) | undefined -} - -export class ObservableStore { - state: State - source$: Observable - sub: Subscription - - constructor({ - source$: miscSource$, - defaultValue, - compareFn, - }: { - source$: Observable | undefined | (() => Observable | undefined) - } & ObservableStoreOptions) { - const source$ = - typeof miscSource$ === "function" ? miscSource$() : miscSource$ - - const hasNoDefinedSource = source$ === undefined - - this.state = { - data: source$ instanceof BehaviorSubject ? source$.value : defaultValue, - status: hasNoDefinedSource ? "success" : "pending", - observableState: hasNoDefinedSource ? "complete" : "live", - error: undefined, - } - - /** - * There is nothing to observe without a source. The state above is already - * final (`complete`), which makes `subscribe` a no-op and therefore makes - * `source$` unreachable. We skip building the pipe chain and opening a - * subscription for a stream that can never emit. - */ - if (hasNoDefinedSource) { - this.source$ = NEVER - this.sub = Subscription.EMPTY - - return - } - - this.source$ = source$.pipe( - distinctUntilChanged(compareFn), - tap({ - complete: () => { - this.state = { - ...this.state, - status: "success", - observableState: "complete", - } - }, - error: (error) => { - this.state = { - ...this.state, - observableState: "error", - status: "error", - error, - } - }, - next: (data) => { - this.state = { ...this.state, data } - }, - }), - share(), - ) - - /** - * @important This eager subscription will optimistically update the state. - * Any observable that is non async (behavior, of(x), etc) will have in fact their state completed - * by the first render cycle. - * Although we only correctly type sync state for `BehaviorSubject` we can in fact get the value in sync - * for more than them. - * Technically the whole pipe chain runs "synchronously". - * - * This is not a guarantee, just that in best case scenario there will be only one render. - * - * An error is returned in the state, so it is handled here rather than - * reported to RxJS as unhandled. - */ - this.sub = this.source$.subscribe({ error: () => {} }) - } - - subscribe = (next: () => void) => { - /** - * The stream may already have completed or errored by the time React - * subscribes. It won't emit again, and subscribing to the shared source - * would only run it a second time. - */ - if (this.state.observableState !== "live") { - return () => {} - } - - const sub = this.source$.subscribe({ - complete: next, - error: next, - next: next, - }) - - return () => { - sub.unsubscribe() - } - } - - getSnapshot = () => { - return this.state - } -} diff --git a/src/lib/binding/useObserve/types.ts b/src/lib/binding/useObserve/types.ts index 96d8bd6..f5a042e 100644 --- a/src/lib/binding/useObserve/types.ts +++ b/src/lib/binding/useObserve/types.ts @@ -1,7 +1,50 @@ -import type { ObservableStoreOptions, State } from "./store" +export interface UseObserveOptions { + /** + * Returned as `data` while the source has no value: before its first + * value, and when it completes or errors without one. Keep it stable: a new + * object on every render is a new `data` on every render. + */ + defaultValue?: DefaultValue + /** + * Tells whether a new value equals the previous one. An equal value does + * not re-render. Defaults to strict equality (`===`). + */ + compareFn?: (a: T, b: T) => boolean +} -export interface UseObserveResult - extends State {} +/** + * The life of the stream, apart from its value: `"live"` while it can + * still emit, `"complete"` once it completed (or when there is no source), + * `"error"` once it errored. + */ +export type ObservableState = "live" | "complete" | "error" -export interface UseObserveOptions - extends Partial> {} +/** + * The state of the source, by whether it has a value, as the queries of + * TanStack Query report theirs. `data` is typed by `status`. + */ +export type UseObserveResult = + | { + /** + * The source has no value: none yet, it completed without one, or + * there is no source. + */ + status: "pending" + data: DefaultValue + error: undefined + observableState: Exclude + } + | { + /** The source has a value. */ + status: "success" + data: Value + error: undefined + observableState: Exclude + } + | { + /** The source errored. `data` keeps its last value, if it had one. */ + status: "error" + data: Value | DefaultValue + error: Error + observableState: "error" + } diff --git a/src/lib/binding/useObserve/useObserve.compare.test.tsx b/src/lib/binding/useObserve/useObserve.compare.test.tsx index 470f16b..a2a2ae6 100644 --- a/src/lib/binding/useObserve/useObserve.compare.test.tsx +++ b/src/lib/binding/useObserve/useObserve.compare.test.tsx @@ -21,7 +21,7 @@ it("should not re-render when the value is same reference", async () => { expect(values[0]).toEqual({ data: undefined, error: undefined, - status: "pending", + status: "success", observableState: "live", }) @@ -254,3 +254,19 @@ describe("Given a forever true compareFn", () => { }) }) }) + +it("should return the same result across renders once the source changed to a BehaviorSubject", () => { + const first$ = new BehaviorSubject(1) + const second$ = new BehaviorSubject(2) + + const { result, rerender } = renderHook(({ source }) => useObserve(source), { + initialProps: { source: first$ }, + }) + + rerender({ source: second$ }) + const resultAfterTheChange = result.current + rerender({ source: second$ }) + + expect(result.current.data).toBe(2) + expect(result.current).toBe(resultAfterTheChange) +}) diff --git a/src/lib/binding/useObserve/useObserve.error.test.tsx b/src/lib/binding/useObserve/useObserve.error.test.tsx index f1d6137..f129280 100644 --- a/src/lib/binding/useObserve/useObserve.error.test.tsx +++ b/src/lib/binding/useObserve/useObserve.error.test.tsx @@ -99,3 +99,35 @@ describe("Given a source that errors after emitting", () => { }) } }) + +describe("Given a compareFn that throws", () => { + for (const { name, wrapper } of modes) { + it(`should keep the last value, return the error, not report it and unsubscribe${name}`, async () => { + const source$ = new BehaviorSubject(1) + const compareFn = (previous: number, next: number) => { + if (next === 2) throw error + + return previous === next + } + + const { result } = renderHook(() => useObserve(source$, { compareFn }), { + wrapper, + }) + + act(() => { + source$.next(2) + }) + + await waitForTimeout(10) + + expect(result.current).toEqual({ + data: 1, + status: "error", + observableState: "error", + error, + }) + expect(onUnhandledError).not.toHaveBeenCalled() + expect(source$.observed).toBe(false) + }) + } +}) diff --git a/src/lib/binding/useObserve/useObserve.lifecycle.test.tsx b/src/lib/binding/useObserve/useObserve.lifecycle.test.tsx new file mode 100644 index 0000000..e283242 --- /dev/null +++ b/src/lib/binding/useObserve/useObserve.lifecycle.test.tsx @@ -0,0 +1,602 @@ +import { act, render, renderHook } from "@testing-library/react" +import { + Activity, + Component, + type ReactNode, + StrictMode, + Suspense, + startTransition, + use, + useLayoutEffect, + useState, +} from "react" +import { + BehaviorSubject, + concat, + map, + NEVER, + ObjectUnsubscribedError, + type Observable, + of, + Subject, +} from "rxjs" +import { afterEach, describe, expect, it, vi } from "vitest" +import { countSubscriptions } from "../../../tests/liveQuery" +import { useObserve } from "./useObserve" + +const createPendingPromise = () => { + let resolve = () => {} + const promise = new Promise((resolvePromise) => { + resolve = resolvePromise + }) + + return { promise, resolve } +} + +class CatchError extends Component< + { children: ReactNode }, + { hasError: boolean } +> { + state = { hasError: false } + + static getDerivedStateFromError() { + return { hasError: true } + } + + render() { + return this.state.hasError ? null : this.props.children + } +} + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe("Given a render that React commits", () => { + it("subscribes once to the source while mounted, and unsubscribes once unmounted", () => { + const { counted$, subscriptions } = countSubscriptions( + new BehaviorSubject(1), + ) + + function Observer() { + "use no memo" + const { data } = useObserve(counted$) + + return <>{data} + } + + const { unmount, container } = render() + + expect(container.textContent).toBe("1") + expect(subscriptions).toEqual({ made: 1, open: 1 }) + + unmount() + + expect(subscriptions.open).toBe(0) + }) + + it("subscribes to the new source once the deps change, and unsubscribes from the old one", () => { + const first = countSubscriptions(new BehaviorSubject(1)) + const second = countSubscriptions(new BehaviorSubject(2)) + + function Observer({ source }: { source: "first" | "second" }) { + "use no memo" + const { data } = useObserve( + () => (source === "first" ? first.counted$ : second.counted$), + [source], + ) + + return <>{data} + } + + const { rerender, container } = render() + + rerender() + + expect(container.textContent).toBe("2") + expect(first.subscriptions).toEqual({ made: 1, open: 0 }) + expect(second.subscriptions).toEqual({ made: 1, open: 1 }) + }) + + it("renders the value of a BehaviorSubject on the first render, and renders once", () => { + const statuses: string[] = [] + const source$ = new BehaviorSubject("value") + + function Observer() { + "use no memo" + const { data, status } = useObserve(source$) + statuses.push(`${status}:${data}`) + + return null + } + + render() + + expect(statuses).toEqual(["success:value"]) + }) +}) + +describe("Given an observable created during render", () => { + it("makes React throw Too many re-renders once the component renders again", () => { + vi.spyOn(console, "error").mockImplementation(() => {}) + const caught: unknown[] = [] + const subject = new BehaviorSubject(1) + + class Boundary extends Component< + { children: ReactNode }, + { hasError: boolean } + > { + state = { hasError: false } + + static getDerivedStateFromError() { + return { hasError: true } + } + + componentDidCatch(error: unknown) { + caught.push(error) + } + + render() { + return this.state.hasError ? null : this.props.children + } + } + + function Observer() { + "use no memo" + const { data } = useObserve(subject.pipe(map((value) => value * 2))) + + return <>{data} + } + + render( + + + , + ) + + expect(caught).toEqual([ + expect.objectContaining({ + message: expect.stringContaining("Too many re-renders"), + }), + ]) + }) +}) + +describe("Given a render that React throws away", () => { + it("subscribes to nothing for a mount that a Suspense boundary threw away", async () => { + const { counted$, subscriptions } = countSubscriptions( + new BehaviorSubject(1), + ) + const { promise, resolve } = createPendingPromise() + + function Suspends() { + "use no memo" + use(promise) + + return null + } + + function Observer() { + "use no memo" + useObserve(counted$) + + return null + } + + const { unmount } = await act(async () => + render( + + + + , + ), + ) + + expect(subscriptions.made).toBe(0) + + await act(async () => { + resolve() + await promise + }) + + expect(subscriptions).toEqual({ made: 1, open: 1 }) + + unmount() + + expect(subscriptions.open).toBe(0) + }) + + it("subscribes to nothing for a render that an error boundary caught", () => { + const { counted$, subscriptions } = countSubscriptions( + new BehaviorSubject(1), + ) + vi.spyOn(console, "error").mockImplementation(() => {}) + + function Throws(): ReactNode { + "use no memo" + useObserve(counted$) + + throw new Error("render failed") + } + + render( + + + , + ) + + expect(subscriptions.made).toBe(0) + }) + + it("subscribes to nothing for the render of a transition that React abandoned", async () => { + const sources = [1, 2, 3].map((value) => + countSubscriptions(new BehaviorSubject(value)), + ) + const pending = createPendingPromise() + let setStep = (_step: number) => {} + + function Suspends({ step }: { step: number }) { + "use no memo" + if (step === 1) use(pending.promise) + + return null + } + + function Observer() { + "use no memo" + const [step, setStepState] = useState(0) + setStep = setStepState + + const { data } = useObserve(() => sources[step]?.counted$, [step]) + + return ( + <> + {data} + + + ) + } + + const { unmount, container } = render( + + + , + ) + + await act(async () => { + startTransition(() => setStep(1)) + }) + await act(async () => { + setStep(2) + }) + + expect(container.textContent).toBe("3") + expect(sources.map(({ subscriptions }) => subscriptions)).toEqual([ + { made: 1, open: 0 }, + { made: 0, open: 0 }, + { made: 1, open: 1 }, + ]) + + unmount() + }) + + it("subscribes to nothing for a mount in a hidden Activity, until it shows", async () => { + const { counted$, subscriptions } = countSubscriptions( + new BehaviorSubject(1), + ) + + function Observer() { + "use no memo" + useObserve(counted$) + + return null + } + + const App = ({ mode }: { mode: "visible" | "hidden" }) => ( + + + + ) + + const { rerender, unmount } = await act(async () => + render(), + ) + + expect(subscriptions.made).toBe(0) + + await act(async () => { + rerender() + }) + + expect(subscriptions).toEqual({ made: 1, open: 1 }) + + unmount() + + expect(subscriptions.open).toBe(0) + }) +}) + +describe("Given a transition that suspends, then an unrelated urgent render", () => { + it("keeps the committed subscription, and subscribes once to the source of the transition", async () => { + const sources = [0, 1].map((value) => + countSubscriptions(new BehaviorSubject(value)), + ) + const pending = createPendingPromise() + let setStep = (_step: number) => {} + let setUnrelated = (_value: number) => {} + + function Suspends({ step }: { step: number }) { + "use no memo" + if (step === 1) use(pending.promise) + + return null + } + + function Observer() { + "use no memo" + const [step, setStepState] = useState(0) + const [unrelated, setUnrelatedState] = useState(0) + setStep = setStepState + setUnrelated = setUnrelatedState + + const { data } = useObserve(() => sources[step]?.counted$, [step]) + + return ( + <> + {`${data}:${unrelated}`} + + + ) + } + + const { container, unmount } = render( + + + , + ) + + await act(async () => { + startTransition(() => setStep(1)) + }) + await act(async () => { + setUnrelated(1) + }) + + expect(container.textContent).toBe("0:1") + + await act(async () => { + pending.resolve() + await pending.promise + }) + + expect(container.textContent).toBe("1:1") + expect(sources.map(({ subscriptions }) => subscriptions)).toEqual([ + { made: 1, open: 0 }, + { made: 1, open: 1 }, + ]) + + unmount() + }) +}) + +describe("Given deps that leave a source, then come back to it", () => { + it("subscribes again to a source that completed", () => { + const a = countSubscriptions(of("a")) + const b$ = new BehaviorSubject("b") + + function Observer({ which }: { which: "a" | "b" }) { + "use no memo" + const { data, status } = useObserve( + () => (which === "a" ? a.counted$ : b$), + [which], + ) + + return <>{`${status}:${data}`} + } + + const { rerender, container } = render() + + expect(container.textContent).toBe("success:a") + + rerender() + act(() => { + b$.next("b2") + }) + rerender() + + expect(container.textContent).toBe("success:a") + expect(a.subscriptions.made).toBe(2) + }) + + it("subscribes again when the factory returns the same observable for new deps", () => { + const { counted$, subscriptions } = countSubscriptions(of(1)) + + function Observer({ attempt }: { attempt: number }) { + "use no memo" + useObserve(() => counted$, [attempt]) + + return null + } + + const { rerender } = render() + + rerender() + + expect(subscriptions.made).toBe(2) + }) +}) + +describe("Given a source with a value, then a source without one", () => { + it("is pending for the new source", () => { + const first$: Observable = new BehaviorSubject("first") + const second$ = new Subject() + + const { result, rerender } = renderHook( + ({ source }) => useObserve(source), + { initialProps: { source: first$ } }, + ) + + rerender({ source: second$ }) + + expect(result.current).toMatchObject({ status: "pending", data: undefined }) + }) +}) + +describe("Given a BehaviorSubject whose value changes between render and subscription", () => { + it("shows the new value", () => { + const subject = new BehaviorSubject(1) + + function ChangesTheValue() { + "use no memo" + useLayoutEffect(() => { + subject.next(2) + }, []) + + return null + } + + function Observer() { + "use no memo" + const { data } = useObserve(subject) + + return ( + <> + {data} + + + ) + } + + const { container } = render() + + expect(container.textContent).toBe("2") + }) +}) + +describe("Given a closed BehaviorSubject", () => { + it("returns an error without throwing, on the first render", () => { + const subject = new BehaviorSubject(1) + subject.unsubscribe() + const statuses: string[] = [] + + const { result } = renderHook(() => { + const value = useObserve(subject) + statuses.push(value.status) + + return value + }) + + expect(statuses).toEqual(["error"]) + expect(result.current.error).toBeInstanceOf(ObjectUnsubscribedError) + }) +}) + +describe("Given a Suspense boundary that suspends again", () => { + it("keeps the subscription while its content is hidden", async () => { + const { counted$, subscriptions } = countSubscriptions(new Subject()) + const pending = createPendingPromise() + let suspend = (_shouldSuspend: boolean) => {} + + function Suspends({ shouldSuspend }: { shouldSuspend: boolean }) { + "use no memo" + if (shouldSuspend) use(pending.promise) + + return null + } + + function Observer() { + "use no memo" + useObserve(counted$) + + return null + } + + function App() { + "use no memo" + const [shouldSuspend, setShouldSuspend] = useState(false) + suspend = setShouldSuspend + + return ( + + + + + ) + } + + render() + + expect(subscriptions).toEqual({ made: 1, open: 1 }) + + await act(async () => { + suspend(true) + }) + + expect(subscriptions).toEqual({ made: 1, open: 1 }) + + await act(async () => { + pending.resolve() + await pending.promise + }) + + expect(subscriptions).toEqual({ made: 1, open: 1 }) + }) +}) + +describe("Given a source that completes, and React runs the effect again", () => { + it("subscribes once under StrictMode", () => { + const { counted$, subscriptions } = countSubscriptions(of(1)) + + const { result } = renderHook(() => useObserve(counted$), { + wrapper: StrictMode, + }) + + expect(result.current.data).toBe(1) + expect(subscriptions.made).toBe(1) + }) + + it("subscribes once when an Activity shows the component again", async () => { + const { counted$, subscriptions } = countSubscriptions(of(1)) + + function Observer() { + "use no memo" + const { data } = useObserve(counted$) + + return <>{data} + } + + const App = ({ mode }: { mode: "visible" | "hidden" }) => ( + + + + ) + + const { rerender, container } = render() + + await act(async () => { + rerender() + }) + await act(async () => { + rerender() + }) + + expect(container.textContent).toBe("1") + expect(subscriptions.made).toBe(1) + }) +}) + +describe("Given a defaultValue written inline", () => { + it("returns the same result across renders while the source has a value", () => { + const source$ = concat(of(1), NEVER) + + const { result, rerender } = renderHook(() => + useObserve(source$, { defaultValue: [] as number[] }), + ) + + const resultWithAValue = result.current + rerender() + + expect(resultWithAValue.status).toBe("success") + expect(result.current).toBe(resultWithAValue) + }) +}) diff --git a/src/lib/binding/useObserve/useObserve.selector.test.tsx b/src/lib/binding/useObserve/useObserve.selector.test.tsx index 139ecf0..c7a261e 100644 --- a/src/lib/binding/useObserve/useObserve.selector.test.tsx +++ b/src/lib/binding/useObserve/useObserve.selector.test.tsx @@ -20,8 +20,7 @@ it("should return the selected keys", async () => { values.push(value.data) }, {}) - expect(values[0]).toEqual({ foo: "foo" }) - expect(values.length).toBe(1) + expect(values).toEqual([undefined, { foo: "foo" }]) }) it("should not re-render when the selected keys don't change", async () => { @@ -44,18 +43,20 @@ it("should not re-render when the selected keys don't change", async () => { }, [value]) }, {}) - expect(values[0]).toEqual({ + expect(values.at(-1)).toEqual({ data: { a: "a" }, error: undefined, - status: "pending", + status: "success", observableState: "live", }) + const renders = values.length + act(() => { source$.next({ a: "a", b: "c" }) }) - expect(values.length).toBe(1) + expect(values.length).toBe(renders) }) it("should re-render when the selected keys change", async () => { @@ -78,12 +79,14 @@ it("should re-render when the selected keys change", async () => { }, [value]) }, {}) - expect(values[0]).toEqual({ a: "a" }) + expect(values.at(-1)).toEqual({ a: "a" }) + + const renders = values.length act(() => { source$.next({ a: "b", b: "c" }) }) - expect(values[1]).toEqual({ a: "b" }) - expect(values.length).toBe(2) + expect(values.at(-1)).toEqual({ a: "b" }) + expect(values.length).toBe(renders + 1) }) diff --git a/src/lib/binding/useObserve/useObserve.server.test.tsx b/src/lib/binding/useObserve/useObserve.server.test.tsx new file mode 100644 index 0000000..0821ae8 --- /dev/null +++ b/src/lib/binding/useObserve/useObserve.server.test.tsx @@ -0,0 +1,38 @@ +// @vitest-environment node +import { renderToString } from "react-dom/server" +import { BehaviorSubject, concat, NEVER, of } from "rxjs" +import { describe, expect, it } from "vitest" +import { countSubscriptions } from "../../../tests/liveQuery" +import { useObserve } from "./useObserve" + +describe("Given a server render", () => { + it("renders the value of a BehaviorSubject without subscribing to it", () => { + const subject = new BehaviorSubject(1) + + function Observer() { + "use no memo" + const { data } = useObserve(subject) + + return <>{data} + } + + expect(renderToString()).toBe("1") + expect(subject.observed).toBe(false) + }) + + it("renders the default value of a source that holds no value, without subscribing to it", () => { + const { counted$, subscriptions } = countSubscriptions( + concat(of("first"), NEVER), + ) + + function Observer() { + "use no memo" + const { data, status } = useObserve(counted$, { defaultValue: "none" }) + + return <>{`${status}:${data}`} + } + + expect(renderToString()).toBe("pending:none") + expect(subscriptions.made).toBe(0) + }) +}) diff --git a/src/lib/binding/useObserve/useObserve.test.tsx b/src/lib/binding/useObserve/useObserve.test.tsx index 1eaf234..fcbf6fe 100644 --- a/src/lib/binding/useObserve/useObserve.test.tsx +++ b/src/lib/binding/useObserve/useObserve.test.tsx @@ -1,6 +1,14 @@ import { cleanup, render, renderHook } from "@testing-library/react" import React, { act, memo, useEffect, useState } from "react" -import { BehaviorSubject, map, type Observable, of, Subject, timer } from "rxjs" +import { + BehaviorSubject, + defer, + map, + type Observable, + of, + Subject, + timer, +} from "rxjs" import { afterEach, describe, expect, expectTypeOf, it } from "vitest" import { waitForTimeout } from "../../../tests/utils" import { useConstant } from "../../utils/react/useConstant" @@ -13,7 +21,7 @@ afterEach(() => { describe("useObserve", () => { describe("Given a non BehaviorSubject observable", () => { - it("should return `foo` as first render cycle due to internal optimization and should only have one render cycle", async () => { + it("should be pending on the first render, then return the value the source emits on subscription", async () => { const values: Array> = [] const source$ = of("foo") @@ -21,9 +29,10 @@ describe("useObserve", () => { values.push(useObserve(source$)) }, {}) - expect(values[0]?.data).toBe("foo") - - expect(values.length).toBe(1) + expect(values.map(({ status, data }) => [status, data])).toEqual([ + ["pending", undefined], + ["success", "foo"], + ]) }) }) @@ -95,7 +104,7 @@ describe("useObserve", () => { expect(result.current).toEqual({ data: 0, - status: "pending", + status: "success", observableState: "live", error: undefined, }) @@ -106,7 +115,7 @@ describe("useObserve", () => { expect(result.current).toEqual({ data: 1, - status: "pending", + status: "success", observableState: "live", error: undefined, }) @@ -222,7 +231,7 @@ describe("useObserve", () => { expect(await findByText("10")).toBeDefined() }) - it("does not re-render when observer complete", async () => { + it("re-renders when the source completes", async () => { const subject = new Subject() let numberOfRenders = 0 @@ -262,6 +271,77 @@ describe("useObserve", () => { expect(numberOfRenders).toBe(3) }) + describe("Given a status check", () => { + it("should type data as a value once status is success", () => { + const source$ = of(1) + + renderHook(() => { + const result = useObserve(source$, { defaultValue: null }) + + if (result.status === "success") { + expectTypeOf(result.data).toEqualTypeOf() + } else if (result.status === "pending") { + expectTypeOf(result.data).toEqualTypeOf() + } else { + expectTypeOf(result.data).toEqualTypeOf() + } + }) + }) + }) + + describe("Given a BehaviorSubject that already errored", () => { + it("should return the error without throwing", () => { + const error = new Error("boom") + const subject = new BehaviorSubject(1) + subject.error(error) + + const { result } = renderHook(() => useObserve(subject)) + + expect(result.current).toEqual({ + data: undefined, + status: "error", + observableState: "error", + error, + }) + }) + }) + + describe("Given a dependency that is NaN", () => { + it("should subscribe once across renders", () => { + let subscriptions = 0 + const source$ = new BehaviorSubject(1) + const counted$ = defer(() => { + subscriptions++ + + return source$ + }) + + const { rerender } = renderHook(() => + useObserve(() => counted$, [Number.NaN]), + ) + + rerender() + rerender() + + expect(subscriptions).toBe(1) + }) + }) + + describe("Given a defaultValue that changes before the first value", () => { + it("should return the new defaultValue", () => { + const source$ = new Subject() + + const { result, rerender } = renderHook( + ({ fallback }) => useObserve(source$, { defaultValue: fallback }), + { initialProps: { fallback: "a" } }, + ) + + rerender({ fallback: "b" }) + + expect(result.current.data).toBe("b") + }) + }) + describe("Given a factory that may or may not return an observable", () => { it("should type return correctly", async () => { renderHook(() => { @@ -285,7 +365,12 @@ describe("useObserve", () => { undefined, ) - values.push(useObserve(() => res, [res])) + // committed renders only: a deps change runs the component twice + const result = useObserve(() => res, [res]) + + useEffect(() => { + values.push(result) + }, [result]) useEffect(() => { setTimeout(() => { @@ -301,14 +386,13 @@ describe("useObserve", () => { expect(values).toEqual([ { data: undefined, - status: "success", + status: "pending", observableState: "complete", error: undefined, }, - // still live because not completed { data: 1, - status: "pending", + status: "success", observableState: "live", error: undefined, }, @@ -318,21 +402,21 @@ describe("useObserve", () => { describe("Given a source that may or may not be an observable", () => { it("should type return correctly", async () => { + const source$ = of(1) as Observable | undefined + const subject$ = new BehaviorSubject(1) as + | BehaviorSubject + | undefined + renderHook(() => { - const value = useObserve(of(1) as Observable | undefined) + const value = useObserve(source$) expectTypeOf(value.data).toEqualTypeOf() - const withDefaultValue = useObserve( - of(1) as Observable | undefined, - { defaultValue: null }, - ) + const withDefaultValue = useObserve(source$, { defaultValue: null }) expectTypeOf(withDefaultValue.data).toEqualTypeOf() - const subject = useObserve( - new BehaviorSubject(1) as BehaviorSubject | undefined, - ) + const subject = useObserve(subject$) expectTypeOf(subject.data).toEqualTypeOf() }, {}) @@ -361,7 +445,7 @@ describe("useObserve", () => { expect(result.current).toEqual({ data: undefined, - status: "success", + status: "pending", observableState: "complete", error: undefined, }) @@ -391,7 +475,7 @@ describe("useObserve", () => { expect(result.current).toEqual({ data: null, - status: "success", + status: "pending", observableState: "complete", error: undefined, }) @@ -406,7 +490,12 @@ describe("useObserve", () => { BehaviorSubject | undefined >(undefined) - values.push(useObserve(source$)) + // committed renders only: a deps change runs the component twice + const result = useObserve(source$) + + useEffect(() => { + values.push(result) + }, [result]) useEffect(() => { setTimeout(() => { @@ -422,14 +511,13 @@ describe("useObserve", () => { expect(values).toEqual([ { data: undefined, - status: "success", + status: "pending", observableState: "complete", error: undefined, }, - // still live because not completed { data: 1, - status: "pending", + status: "success", observableState: "live", error: undefined, }, diff --git a/src/lib/binding/useObserve/useObserve.ts b/src/lib/binding/useObserve/useObserve.ts index 8922c6d..7074bdf 100644 --- a/src/lib/binding/useObserve/useObserve.ts +++ b/src/lib/binding/useObserve/useObserve.ts @@ -1,13 +1,120 @@ -import { type DependencyList, useSyncExternalStore } from "react" -import type { BehaviorSubject, Observable } from "rxjs" -import type { UseObserveResult } from "./types" -import { useStore } from "./useStore" +import { + type DependencyList, + useEffect, + useMemo, + useRef, + useState, +} from "react" +import { BehaviorSubject, filter, type Observable } from "rxjs" +import { useLiveRef } from "../../utils/react/useLiveRef" +import type { UseObserveOptions, UseObserveResult } from "./types" -export type { UseObserveOptions, UseObserveResult } from "./types" +export type { + ObservableState, + UseObserveOptions, + UseObserveResult, +} from "./types" -interface Option { - defaultValue: R - compareFn?: (a: T, b: T) => boolean +type OptionsWithDefaultValue = UseObserveOptions< + T, + DefaultValue +> & { defaultValue: DefaultValue } + +type OptionsWithoutDefaultValue = Omit< + UseObserveOptions, + "defaultValue" +> + +/** Whether the source has a value, and how its stream ended. */ +type SourceState = ( + | { observableState: "live" | "complete" } + | { observableState: "error"; error: unknown } +) & + ({ hasValue: false } | { hasValue: true; value: T }) + +/** + * One observation of a source, created when the deps change. It is kept in + * state, so React keeps it across renders, and across the effects it runs + * again (`StrictMode` in development, an `` shown again). A deps + * change starts a new one, even when the factory returns the same + * observable. + */ +type Observation = { + deps: DependencyList + source: Observable | undefined + /** What render shows of the source before the effect subscribes. */ + initialState: SourceState +} + +const observe = ( + source$: Observable | undefined | (() => Observable | undefined), + deps: DependencyList, +): Observation => { + const source = typeof source$ === "function" ? source$() : source$ + + return { deps, source, initialState: getInitialState(source) } +} + +const areDepsEqual = (a: DependencyList, b: DependencyList) => + a.length === b.length && a.every((dep, index) => Object.is(dep, b[index])) + +/** + * Only the value a `BehaviorSubject` holds (a signal is one) is read + * without a subscription. + */ +const getInitialState = ( + source: Observable | undefined, +): SourceState => { + if (source === undefined) { + return { observableState: "complete", hasValue: false } + } + + if (source instanceof BehaviorSubject) { + try { + return { + observableState: "live", + hasValue: true, + value: source.getValue(), + } + } catch (error) { + // An errored subject throws its error, a closed one `ObjectUnsubscribedError`. + return { observableState: "error", error, hasValue: false } + } + } + + return { observableState: "live", hasValue: false } +} + +const isStrictlyEqual = (a: unknown, b: unknown) => a === b + +const toResult = ( + state: SourceState, + defaultValue: DefaultValue, +): UseObserveResult => { + if (state.observableState === "error") { + return { + status: "error", + data: state.hasValue ? state.value : defaultValue, + error: state.error, + observableState: "error", + } + } + + if (state.hasValue) { + return { + status: "success", + data: state.value, + error: undefined, + observableState: state.observableState, + } + } + + return { + status: "pending", + data: defaultValue, + error: undefined, + observableState: state.observableState, + } } /** @@ -23,16 +130,21 @@ export function useObserve( export function useObserve( source: undefined, - options: Option, + options: OptionsWithDefaultValue, ): UseObserveResult +/** + * A `BehaviorSubject` always holds a value, so `data` is typed as one. A + * subject that already errored, or is closed, has none: `status` is + * `"error"` and `data` is `undefined`. + */ export function useObserve( source: BehaviorSubject, ): UseObserveResult export function useObserve( source: BehaviorSubject, - options: Omit, "defaultValue">, + options: OptionsWithoutDefaultValue, ): UseObserveResult export function useObserve( @@ -51,38 +163,36 @@ export function useObserve( export function useObserve( source: Observable | undefined, - options: Option, + options: OptionsWithDefaultValue, ): UseObserveResult export function useObserve( source: Observable | undefined, - options: Omit, "defaultValue">, + options: OptionsWithoutDefaultValue, ): UseObserveResult export function useObserve( source: () => Observable, - options: Option, + options: OptionsWithDefaultValue, deps: DependencyList, ): UseObserveResult export function useObserve( source: () => Observable | undefined, - options: Option, + options: OptionsWithDefaultValue, deps: DependencyList, ): UseObserveResult export function useObserve( source$: Observable | undefined | (() => Observable | undefined), - optionsOrDeps?: Partial> | DependencyList, + optionsOrDeps?: UseObserveOptions | DependencyList, maybeDeps?: DependencyList, ): UseObserveResult { - const options = + const options: UseObserveOptions = optionsOrDeps != null && !Array.isArray(optionsOrDeps) - ? (optionsOrDeps as Partial>) - : ({ - defaultValue: undefined, - compareFn: undefined, - } satisfies Partial>) + ? // `Array.isArray` does not narrow out a readonly `DependencyList`. + (optionsOrDeps as UseObserveOptions) + : {} const deps = !maybeDeps && Array.isArray(optionsOrDeps) ? optionsOrDeps @@ -90,13 +200,114 @@ export function useObserve( ? (maybeDeps ?? []) : [source$] - const store = useStore(source$, options, deps) + const [state, setState] = useState(() => { + const observation = observe(source$, deps) + + return { observation, sourceState: observation.initialState } + }) + let { observation, sourceState } = state + + /** + * New deps start a new observation during render, and React renders again + * at once. A source created on every render, such as `source$.pipe(...)` + * written in the component, therefore makes React throw "Too many + * re-renders" rather than subscribe again without end. + */ + if (!areDepsEqual(observation.deps, deps)) { + observation = observe(source$, deps) + sourceState = observation.initialState + setState({ observation, sourceState }) + } + const compareFnRef = useLiveRef(options.compareFn) + /** + * The latest state of an observation, as its subscription set it. An effect + * that React runs again for the same observation starts from it, and does + * not subscribe again to a source that already completed or errored: a cold + * source would start over. + */ + const latestRef = useRef< + { observation: Observation; sourceState: SourceState } | undefined + >(undefined) - const result = useSyncExternalStore( - store.subscribe, - store.getSnapshot, - store.getSnapshot, + /** + * The source is subscribed after commit only, so a render that React throws + * away, and a server render, start nothing. + */ + useEffect( + function observeSource() { + const { source } = observation + let latest = + latestRef.current?.observation === observation + ? latestRef.current.sourceState + : observation.initialState + + if (!source || latest.observableState !== "live") return + + /** + * Only this subscription changes the state of its observation, so a + * value that changes nothing, such as the one a `BehaviorSubject` + * emits on subscription, sets no state and renders nothing. + */ + const commit = (next: SourceState) => { + latest = next + latestRef.current = { observation, sourceState: next } + setState({ observation, sourceState: next }) + } + + /** + * The comparison runs in an operator, so a `compareFn` that throws + * errors the stream instead of being reported as unhandled. + */ + const changedValue$ = source.pipe( + filter(function isChangedValue(value) { + const isEqual = compareFnRef.current ?? isStrictlyEqual + + return !(latest.hasValue && isEqual(latest.value, value)) + }), + ) + + const subscription = changedValue$.subscribe({ + next: (value) => { + commit({ observableState: "live", hasValue: true, value }) + }, + error: (error: unknown) => { + commit( + latest.hasValue + ? { + observableState: "error", + error, + hasValue: true, + value: latest.value, + } + : { observableState: "error", error, hasValue: false }, + ) + }, + complete: () => { + commit( + latest.hasValue + ? { + observableState: "complete", + hasValue: true, + value: latest.value, + } + : { observableState: "complete", hasValue: false }, + ) + }, + }) + + return () => { + subscription.unsubscribe() + } + }, + [observation, compareFnRef], ) - return result + const shownDefaultValue = sourceState.hasValue + ? undefined + : options.defaultValue + + return useMemo( + () => toResult(sourceState, shownDefaultValue), + [sourceState, shownDefaultValue], + ) } diff --git a/src/lib/binding/useObserve/useStore.ts b/src/lib/binding/useObserve/useStore.ts deleted file mode 100644 index 8428863..0000000 --- a/src/lib/binding/useObserve/useStore.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { type DependencyList, useEffect, useRef } from "react" -import type { Observable } from "rxjs" -import { arrayEqual, useLiveRef } from "../../utils" -import { ObservableStore } from "./store" -import type { UseObserveOptions } from "./types" - -type StoreReference = { - deps: DependencyList - store: ObservableStore -} - -/** - * Mechanism to initialize / retrieve an existing observable store. - * - * - We cannot use `useMemo` because it is theoretically not stable. We need stability, - * not performance optimization. - * - Using `useState` would make the API not sync (or optimistically return the wrong value). - * We want the returned value of a render cycle to be derived from the given arguments. `useState` - * would force us to update the store asynchronously in a useEffect. Losing at least one render cycle. - * - We are left with using refs to hold the latest references. We use comparison with given deps as well. - * We are re-creating store during render cycles which is normally not recommended. - * However this is "okay" since it is to be used inside a useSyncExternalStore and not directly in a render. - */ -export const useStore = ( - source$: Observable | undefined | (() => Observable | undefined), - options: UseObserveOptions, - deps: DependencyList, -): ObservableStore => { - const optionsRef = useLiveRef(options) - const storeRef = useRef | undefined>( - undefined, - ) - - if (!storeRef.current || !arrayEqual(deps, storeRef.current.deps)) { - /** - * The store subscribes in its constructor, during render, while the ref - * still holds the last committed options. The values that a synchronous - * source emits then go through the `compareFn` of this render. - */ - let isCreating = true - const store = new ObservableStore({ - source$, - defaultValue: options.defaultValue, - compareFn: (a, b) => { - const { compareFn } = isCreating ? options : optionsRef.current - - return compareFn?.(a, b) ?? a === b - }, - }) - isCreating = false - - storeRef.current = { deps, store } - } - - const store = storeRef.current.store - - useEffect( - () => () => { - store.sub.unsubscribe() - }, - [store], - ) - - return store -} diff --git a/src/lib/state/react/usePersistSignals.server.test.tsx b/src/lib/state/react/usePersistSignals.server.test.tsx new file mode 100644 index 0000000..3b663ba --- /dev/null +++ b/src/lib/state/react/usePersistSignals.server.test.tsx @@ -0,0 +1,29 @@ +// @vitest-environment node +import { renderToString } from "react-dom/server" +import { describe, expect, it, vi } from "vitest" +import { signal } from "../Signal" +import { usePersistSignals } from "./usePersistSignals" + +describe("Given a server render", () => { + it("should not read or write the adapter", () => { + const signalA = signal({ default: 0, key: "a" }) + const adapter = { + getItem: vi.fn(async () => undefined), + setItem: vi.fn(async () => undefined), + } + + function App() { + "use no memo" + const { isHydrated } = usePersistSignals({ + entries: [{ signal: signalA, version: 0 }], + adapter, + }) + + return <>{String(isHydrated)} + } + + expect(renderToString()).toBe("false") + expect(adapter.getItem).not.toHaveBeenCalled() + expect(adapter.setItem).not.toHaveBeenCalled() + }) +}) diff --git a/src/lib/state/react/usePersistSignals.test.tsx b/src/lib/state/react/usePersistSignals.test.tsx index df94a4f..13b5d65 100644 --- a/src/lib/state/react/usePersistSignals.test.tsx +++ b/src/lib/state/react/usePersistSignals.test.tsx @@ -1,5 +1,5 @@ -import { renderHook, waitFor } from "@testing-library/react" -import { StrictMode } from "react" +import { act, render, renderHook, waitFor } from "@testing-library/react" +import { StrictMode, Suspense, use, useState } from "react" import { createRoot } from "react-dom/client" import { describe, expect, it, vi } from "vitest" import { waitForTimeout } from "../../../tests/utils" @@ -347,8 +347,8 @@ describe("Given StrictMode", () => { describe("Given a mount with browser timing", () => { /** - * Outside `act`, effects run after pending promises resolve, as in a - * browser, so hydration can finish before the mount effects run. + * Outside `act`, React runs the effects as a browser does, after pending + * promises resolve. */ it("should hydrate once and call onHydrated once", { timeout: 3000, @@ -747,3 +747,142 @@ describe("Given an entry added later with nothing stored", () => { expect(signalB.getValue()).toBe(3) }) }) + +describe("Given a render that React throws away", () => { + it("should neither read the adapter for it nor save the signals after unmount", { + timeout: 3000, + }, async () => { + const signalA = signal({ default: 0, key: "a" }) + const adapter = createMemoryAdapter({ a: storedValue(1) }) + const entries: Entries = [{ signal: signalA, version: 0 }] + let resolve = () => {} + const promise = new Promise((resolvePromise) => { + resolve = resolvePromise + }) + + function Suspends() { + "use no memo" + use(promise) + + return null + } + + function App() { + "use no memo" + usePersistSignals({ entries, adapter }) + + return + } + + const { unmount } = await act(async () => + render( + + + , + ), + ) + + expect(adapter.calls.getItem).toBe(0) + + await act(async () => { + resolve() + await promise + }) + await waitFor(() => expect(signalA.getValue()).toBe(1)) + await waitForTimeout(600) + + expect(adapter.calls.getItem).toBe(1) + + unmount() + adapter.calls.setItem = 0 + signalA.update(42) + await waitForTimeout(700) + + expect(adapter.calls.setItem).toBe(0) + }) +}) + +describe("Given a Suspense boundary that suspends again after hydration", () => { + it("should keep a signal update made while its content is hidden, and call onHydrated once", { + timeout: 3000, + }, async () => { + const signalA = signal({ default: 0, key: "a" }) + const adapter = createMemoryAdapter({ a: storedValue(1) }) + const onHydrated = vi.fn() + const entries: Entries = [{ signal: signalA, version: 0 }] + let resolve = () => {} + const promise = new Promise((resolvePromise) => { + resolve = resolvePromise + }) + let suspend = (_shouldSuspend: boolean) => {} + + function Suspends({ shouldSuspend }: { shouldSuspend: boolean }) { + "use no memo" + if (shouldSuspend) use(promise) + + return null + } + + function Persist() { + "use no memo" + usePersistSignals({ entries, adapter, onHydrated }) + + return null + } + + function App() { + "use no memo" + const [shouldSuspend, setShouldSuspend] = useState(false) + suspend = setShouldSuspend + + return ( + + + + + ) + } + + render() + await waitFor(() => expect(signalA.getValue()).toBe(1)) + await waitForTimeout(600) + + await act(async () => { + suspend(true) + }) + signalA.update(42) + await waitForTimeout(600) + await act(async () => { + resolve() + await promise + }) + await waitForTimeout(100) + + expect(signalA.getValue()).toBe(42) + expect(onHydrated).toHaveBeenCalledTimes(1) + }) +}) + +describe("Given a mount", () => { + it("should render its host once before hydration, and once after", async () => { + const signalA = signal({ default: 0, key: "a" }) + const adapter = createMemoryAdapter({ a: storedValue(1) }) + const isHydratedValues: boolean[] = [] + + function Persist() { + "use no memo" + const { isHydrated } = usePersistSignals({ + entries: [{ signal: signalA, version: 0 }], + adapter, + }) + isHydratedValues.push(isHydrated) + + return null + } + + render() + await waitFor(() => expect(isHydratedValues.at(-1)).toBe(true)) + + expect(isHydratedValues).toEqual([false, true]) + }) +}) diff --git a/src/lib/state/react/usePersistSignals.tsx b/src/lib/state/react/usePersistSignals.tsx index 8f75702..946ed2f 100644 --- a/src/lib/state/react/usePersistSignals.tsx +++ b/src/lib/state/react/usePersistSignals.tsx @@ -1,15 +1,24 @@ -import { map, merge, of, scan, switchMap } from "rxjs" +import { + distinctUntilChanged, + map, + merge, + of, + scan, + skip, + startWith, + switchMap, +} from "rxjs" import { useLiveBehaviorSubject } from "../../binding/useLiveBehaviorSubject" import { useObserve } from "../../binding/useObserve/useObserve" import { useLiveRef } from "../../utils/react/useLiveRef" -import { isShallowEqual } from "../../utils/shallowEqual" import type { Adapter } from "../persistence/adapters/Adapter" import { persistSignals } from "../persistence/persistSignals" import type { SignalPersistenceConfig } from "../persistence/types" /** * Hydrates the signals of `entries` from `adapter`, then persists their - * updates to it. + * updates to it. It starts once the component has mounted: a render that + * never commits, and a server render, read and write nothing. * * `isHydrated` becomes `true` once the entries have been hydrated for the * first time. Entries added later do not change it. It is reset when the @@ -50,7 +59,7 @@ export function usePersistSignals({ const adapterSubject = useLiveBehaviorSubject(adapter) const entriesSubject = useLiveBehaviorSubject(entries) - const result = useObserve( + const { data: isHydrated } = useObserve( () => adapterSubject.pipe( /** @@ -92,11 +101,15 @@ export function usePersistSignals({ }), ) }), - map((event) => ({ isHydrated: event.type === "hydrated" })), + map((event) => event.type === "hydrated"), + // Only changes from `false`, the value shown before the first one. + startWith(false), + distinctUntilChanged(), + skip(1), ), - { defaultValue: { isHydrated: false }, compareFn: isShallowEqual }, - [adapterSubject, entriesSubject], + { defaultValue: false }, + [adapterSubject, entriesSubject, onHydratedRef], ) - return result.data + return { isHydrated } }