Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
51 changes: 29 additions & 22 deletions gitbook/reactjrx/bindings/react/useobserve.md
Original file line number Diff line number Diff line change
@@ -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?)
Expand All @@ -10,9 +10,12 @@ useObserve(source, optionsOrDeps?, deps?)

```typescript
function App () {
const { data: user } = useObserve(user$)
const { data: user, status } = useObserve(user$)

return <div>current user: { user?.name }</div>
if (status === "error") return <ErrorMessage />
if (status === "pending") return <Spinner />

return <div>current user: { user.name }</div>
}
```

Expand All @@ -23,12 +26,10 @@ function useObserve<T, DefaultValue>(
source: Observable<T> | (() => Observable<T> | undefined) | undefined,
optionsOrDeps?: Options<T, DefaultValue> | 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
Expand All @@ -42,31 +43,37 @@ interface Options<T, DefaultValue> {

* `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.

### Returns

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**&#x20;

* 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 `<Activity>` 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 () {
Expand All @@ -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)
Expand All @@ -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<number>(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 (
<div>
Expand All @@ -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" })
Expand Down
27 changes: 21 additions & 6 deletions gitbook/reactjrx/important-considerations.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <Spinner />

return <div>{data}</div>
}
```

### Handle `undefined`

Expand All @@ -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 = () => {
Expand Down
2 changes: 2 additions & 0 deletions gitbook/reactjrx/state-signal/about.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
125 changes: 0 additions & 125 deletions src/lib/binding/useObserve/store.ts

This file was deleted.

53 changes: 48 additions & 5 deletions src/lib/binding/useObserve/types.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,50 @@
import type { ObservableStoreOptions, State } from "./store"
export interface UseObserveOptions<T, DefaultValue> {
/**
* 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<Value, DefaultValue, Error = unknown>
extends State<Value, DefaultValue, Error> {}
/**
* 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<T, DefaultValue>
extends Partial<ObservableStoreOptions<T, DefaultValue>> {}
/**
* 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<Value, DefaultValue, Error = unknown> =
| {
/**
* The source has no value: none yet, it completed without one, or
* there is no source.
*/
status: "pending"
data: DefaultValue
error: undefined
observableState: Exclude<ObservableState, "error">
}
| {
/** The source has a value. */
status: "success"
data: Value
error: undefined
observableState: Exclude<ObservableState, "error">
}
| {
/** The source errored. `data` keeps its last value, if it had one. */
status: "error"
data: Value | DefaultValue
error: Error
observableState: "error"
}
Loading
Loading