Skip to Content
Effetch Query
Queries

Push updates into a query

Update a fetched query's value from pushed events.

Your server announces changes over a WebSocket, and you'd rather apply them than refetch the whole list. A query's live option takes a stream of updates, each a function from the current value to the next one, and applies them between fetches. This page shows how, and how pushes and fetches work together.

The example imports api.ts and todos.ts from Getting started, and socket.ts from Queries from a stream.

Apply pushed changes to a query

With the socketMessages helper from socket.ts, a WebSocket that announces changes to the todo list keeps it current:

live-todos.ts
import * as  from "effect/Schedule";
import * as  from "effect/Schema";
import * as  from "effect/Stream";

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

const  = .([
  .("Saved", { :  }),
  .("Deleted", { : . }),
]);
type  = typeof .;
const  = .(.());

// A change as an update of the list, by id, so applying it twice is safe.
const  =
  (: ) =>
  (: <>): <> => {
    const  = . === "Saved" ? .. : .;
    const  = .(() => . !== );
    return . === "Saved" ? [..., .] : ;
  };

const  = ("wss://api.example.com/todos/changes").(
  .(() => ()),
  .(),
  .(.("5 seconds")),
);

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

Each change becomes an update of the list: a saved todo replaces its old copy, at the end of the list, and a deleted one is removed. On api.query, live is a function of the call's params and query. On Query.make it's a Stream, and on Query.family a function of the member's argument.

The stream runs only while the query is read, and stops about a second after its last reader leaves. Query.fetch doesn't start it: unlike a stream query, a live query's value comes from its fetch.

Pushes and fetches together

A push keeps the value's age, so staleTime and the refetches it drives work as they do without one, and catch changes the stream missed. Make each update idempotent, such as an upsert or a removal by ID, because some are applied twice:

  • A push that comes while a fetch runs is applied to the fetch's result too, which may or may not hold the change.
  • A push that comes after an optimistic update is applied again if the mutation fails and the update is undone.

Three more cases to know:

  • A push with no value to apply to. A push to a query with no value yet, or one that failed, is kept only for a fetch in progress: a fetch that starts after it already holds the change.
  • An update that throws is logged with Effect.logError and skipped.
  • A stream that fails. The error is logged, and pushes stop until the query is next read after its readers leave. Add Stream.retry to subscribe again sooner, as changes does.

What's next

On this page