Skip to content

Variable: createWritableAtom

API / @xmachines/play-atom / createWritableAtom

const createWritableAtom: <T>(initialValue, options?) => Atom<T> = createAtom;

Defined in: play-atom/src/create-writable-atom.ts:50

Builds a WRITABLE atom, and never a computed one.

createAtom carries two signatures: a function argument builds a computed atom, and a value argument builds a writable one. TypeScript reads the signatures in order, so it needs to prove that the argument is NOT a function before it reaches the second one. For a concrete type it proves that at once, and createAtom is then the right call.

For an UNRESOLVED type the proof fails. ReturnType<TMachine["transition"]> inside a generic class is a conditional type that TypeScript cannot evaluate yet, so it cannot rule a function out, it picks the first signature, and the call returns a ReadonlyAtom that carries no set. The error arrives at the assignment, and it names a type that the reader never wrote.

This function states the one signature. The assignment below checks that the signature belongs to createAtom, so the two stay in step and no cast hides a mistake.

Use createAtom everywhere else. Reach for this function when the value type is a type parameter, or a conditional type over one.

A CAUTION: the signature states ONE overload, and the implementation is createAtom itself, which reads a FUNCTION argument as a computed atom. A T that a function satisfies therefore gets a ReadonlyAtom at run time while the type says Atom, and the first set call throws. Hold a function in a wrapper — createWritableAtom({ fn }) — as the value types of this workspace already do.

Type Parameters

Type Parameter
T

Parameters

ParameterTypeDescription
initialValueTThe first value of the atom. It must not be a function.
options?AtomOptions<T>The optional compare function. The default is Object.is.

Returns

Atom<T>

The writable atom.

Example

import { createWritableAtom, type Atom } from "@xmachines/play-atom";
class Holder<T extends { value: unknown }> {
// `createAtom(seed)` would give a ReadonlyAtom<T["value"]> here.
public readonly state: Atom<T["value"]>;
constructor(seed: T["value"]) {
this.state = createWritableAtom(seed);
}
}