Skip to Content
Effetch Query
Queries

Queries from a stream

Make a query from a stream, such as a socket's messages.

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.

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.

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:

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

export class  extends .("SocketClosed")<{
  readonly : 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  = (: string) =>
  .<string, >(() =>
    .(
      .(() => {
        const  = new ();
        . = () =>
          .(, (.));
        . = () =>
          .(
            ,
            .(new ({ : . })),
          );
        return ;
      }),
      () => .(() => .()),
    ),
  );

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

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

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

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

const  = .({ : ., : . });
const  = .(.());

export const  = .({
  : ["prices"],
  : (: string) =>
    (`wss://api.example.com/prices/${}`).(
      .(() => ()),
    ),
  // Subscribes again after a failure, waiting longer each time.
  : .("1 second"),
  : { :  },
});
// 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 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 sends when the query has a schema. The browser shows it, and subscribes again.

Stream query options

A stream query takes the following options:

OptionWhat it does
keyThe query's key. A family's members append their argument.
runThe 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.
retryThe schedule to subscribe again on after a failure, as Stream.retry takes it. Default: the client's queries.defaults.retry, or none.
retryOnMountWhether a failed stream subscribes again when something starts using the query. Default: the client's, or true.
gcTimeHow long the value stays cached after nothing uses the query. Default: 5 minutes.
reactivityKeysReactivity keys that subscribe it again when they're invalidated, as Freshness and refetching describes. Default: none.
schemaHow the latest value crosses to the browser in server rendering.
placeholderA value to show until the first element. See Show a placeholder. 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:

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

import {  } from "@monarcode/effetch";

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

const  = .({ : . });

export const  = .(
  .("GET /jobs/:id/events", { : , : "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 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

On this page