Skip to Content
Effetch Query
Queries

Push updates into a query

Update a fetched query's value from pushed events.

live keeps a fetched value up to date between fetches, from a stream of updates: functions that each take the value and return the next one. With the socketMessages helper from Queries from a stream, a WebSocket that announces changes to the todo list keeps it current:

The examples import api.ts and todos.ts from Getting started, and socket.ts from Queries from a stream.

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  = .(, { : () =>  });

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.

A push to a query with no value yet 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. If the stream 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.

The stream runs only while the query is read: Query.fetch doesn't start it. live works on Query.make as a Stream, and on Query.family and api.query as a function: of the member's argument, or of the call's params and query.