# Queries from a stream (https://effetch-query.monarcode.dev/docs/queries/streams)

Some values arrive as a stream: prices from a WebSocket, or a job's
progress over Server-Sent Events. `Query.stream` makes a query whose value
is a `Stream`'s latest element, and `Query.streamFamily` makes one per
argument. This page shows how, and how a stream query differs from a
fetched one. To keep a fetched value current from pushed events instead,
see [Push updates into a query](https://effetch-query.monarcode.dev/docs/queries/pushes).

A stream runs only while something reads its query, and stops about a
second after the last reader leaves. The value stays cached for `gcTime`,
and the stream starts again for the next reader.

The examples import `todos.ts` from [Getting started](https://effetch-query.monarcode.dev/docs/getting-started).

## Define a stream query

Until the first element, a stream query is `Initial` and waiting:
`useSuspenseQuery` suspends, and `Query.fetch` waits for it. After that,
each element shows as a `Success` stamped with the time it came.

The following example shows prices from a WebSocket. First, `socket.ts`
turns a socket's messages into a stream:

```ts socket.ts
import * as Cause from "effect/Cause";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Queue from "effect/Queue";
import * as Stream from "effect/Stream";

export class SocketClosed extends Data.TaggedError("SocketClosed")<{
  readonly code: number;
}> {}

// A WebSocket's messages. The socket opens when the stream starts and
// closes when it stops; a socket the server closes fails the stream.
export const socketMessages = (url: string) =>
  Stream.callback<string, SocketClosed>((queue) =>
    Effect.acquireRelease(
      Effect.sync(() => {
        const socket = new WebSocket(url);
        socket.onmessage = (event) =>
          Queue.offerUnsafe(queue, String(event.data));
        socket.onclose = (event) =>
          Queue.failCauseUnsafe(
            queue,
            Cause.fail(new SocketClosed({ code: event.code })),
          );
        return socket;
      }),
      (socket) => Effect.sync(() => socket.close()),
    ),
  );
```

Then `prices.ts` defines a stream query per symbol, from those messages:

```ts prices.ts
import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";

import { Query } from "@monarcode/effetch-query";

import { socketMessages } from "./socket.js";

const Price = Schema.Struct({ symbol: Schema.String, price: Schema.Finite });
const decodePrice = Schema.decodeEffect(Schema.fromJsonString(Price));

export const price = Query.streamFamily({
  key: ["prices"],
  run: (symbol: string) =>
    socketMessages(`wss://api.example.com/prices/${symbol}`).pipe(
      Stream.mapEffect((message) => decodePrice(message)),
    ),
  // Subscribes again after a failure, waiting longer each time.
  retry: Schedule.exponential("1 second"),
  schema: { success: Price },
});
// price("ACME") is the query keyed ["prices", "ACME"]
```

Read it as any other query, with `useQuery(price("ACME"))` or
`useSuspenseQuery`.

## How a stream query differs

A stream keeps its query current, so the refetch rules of a fetched query
don't apply to it:

- **It has no `staleTime`.** Nothing refetches it when a component starts
  using it, on focus, on reconnect or on an interval. `Query.refetch`,
  `Query.invalidate` and `Query.reset` subscribe again; `Query.clear`
  stops it until it's read again.
- **A failure shows, unless `retry` says otherwise.** Without `retry`, a
  failed stream shows its failure, with the last element as its previous
  success. With `retry`, it subscribes again on that schedule first. The
  schedule starts over after an element comes through, and defects
  aren't retried.
- **A failed stream subscribes again when a component next starts using
  the query**, unless `retryOnMount` is `false`.
- **A stream that ends keeps its last element.** One that ends with none
  fails with a `NoSuchElementError` defect.
- **`Query.fetch` starts the stream,** since the query's value is its
  elements, and returns the first element, or the latest while the
  stream runs. `Query.prefetch` waits the same way, and returns nothing.
- **Its elements aren't synced with entities,** as
  [Keep copies in sync](https://effetch-query.monarcode.dev/docs/cache/entity-sync) describes for fetched
  queries.
- **A server render shows only what's cached.** `Query.prefetch` on the
  server runs the stream to its first element, which
  [`QueryClient.dehydrate`](https://effetch-query.monarcode.dev/docs/server-rendering) sends when the query
  has a `schema`. The browser shows it, and subscribes again.

## Stream query options

A stream query takes the following options:

| Option           | What it does                                                                                                                                                                            |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `key`            | The query's key. A family's members append their argument.                                                                                                                              |
| `run`            | The stream. For `Query.stream`, a `Stream`, or a function of the run context for a stream that reads other queries. For a family, a function of the argument and the run context.       |
| `retry`          | The schedule to subscribe again on after a failure, as `Stream.retry` takes it. Default: the client's `queries.defaults.retry`, or none.                                                |
| `retryOnMount`   | Whether a failed stream subscribes again when something starts using the query. Default: the client's, or `true`.                                                                       |
| `gcTime`         | How long the value stays cached after nothing uses the query. Default: 5 minutes.                                                                                                       |
| `reactivityKeys` | `Reactivity` keys that subscribe it again when they're invalidated, as [Freshness and refetching](https://effetch-query.monarcode.dev/docs/queries/freshness#refetch-on-effects-reactivity-keys) describes. Default: none. |
| `schema`         | How the latest value crosses to the browser in server rendering.                                                                                                                        |
| `placeholder`    | A value to show until the first element. See [Show a placeholder](https://effetch-query.monarcode.dev/docs/queries/placeholders). Default: none.                                                                           |

## Stream an Effetch endpoint

An Effetch endpoint defined with `stream: "sse"` or `stream: "ndjson"`
makes stream queries through `api.query`, keyed by route:

```ts job-progress.ts
import * as Schema from "effect/Schema";

import { Fetch } from "@monarcode/effetch";

import { api } from "./todos.js";

const Progress = Schema.Struct({ percent: Schema.Finite });

export const jobProgress = api.query(
  Fetch.endpoint("GET /jobs/:id/events", { output: Progress, stream: "sse" }),
);
// jobProgress({ params: { id: "7" } }) holds the latest Fetch.SseEvent.
```

The value is the latest element as Effetch gives it: a `Fetch.SseEvent`
of the `output` for SSE, or the `output` itself for NDJSON. To read only
an event's data in a component, pass `useQuery` a `select` of
`(event) => event.data`, as
[Select part of a value](https://effetch-query.monarcode.dev/docs/react#select-part-of-a-value) shows.

The request runs while the query is read. It takes a stream query's
`retry`, `retryOnMount`, `gcTime` and `reactivityKeys`. Its `placeholder`
is a function of the call's `params` and `query`. As with any endpoint,
it also takes `headers` and `plugins`.

## What's next

- [Push updates into a query](https://effetch-query.monarcode.dev/docs/queries/pushes): keep a fetched value
  current from a stream of changes.
- [Show a placeholder](https://effetch-query.monarcode.dev/docs/queries/placeholders): show a value until the
  first element.
- [Send the cache](https://effetch-query.monarcode.dev/docs/server-rendering): render a stream's first
  element on the server.