# Push updates into a query (https://0758e0c7.effetch-query.pages.dev/docs/queries/pushes)

`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](https://0758e0c7.effetch-query.pages.dev/docs/queries/streams), a WebSocket that announces
changes to the todo list keeps it current:

The examples import `api.ts` and `todos.ts` from [Getting started](https://0758e0c7.effetch-query.pages.dev/docs/getting-started), and `socket.ts` from [Queries from a stream](https://0758e0c7.effetch-query.pages.dev/docs/queries/streams).

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

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

const TodoChange = Schema.Union([
  Schema.TaggedStruct("Saved", { todo: Todo }),
  Schema.TaggedStruct("Deleted", { id: Schema.Finite }),
]);
type TodoChange = typeof TodoChange.Type;
const decodeChange = Schema.decodeEffect(Schema.fromJsonString(TodoChange));

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

const changes = socketMessages("wss://api.example.com/todos/changes").pipe(
  Stream.mapEffect((message) => decodeChange(message)),
  Stream.map(apply),
  Stream.retry(Schedule.spaced("5 seconds")),
);

export const liveTodos = api.query(listTodos, { live: () => changes });
```

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](https://0758e0c7.effetch-query.pages.dev/docs/mutations/optimistic) 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`.