Skip to content

@statesync/jotai


@statesync/jotai / createJotaiSnapshotApplier

Function: createJotaiSnapshotApplier()

ts
function createJotaiSnapshotApplier<State, Data, Atom>(
   store, 
   atom, 
options): SnapshotApplier<Data>;

Defined in: jotai.ts:260

Creates a SnapshotApplier that applies incoming snapshots into a Jotai atom via a Jotai store.

This is a framework adapter: it only focuses on how to apply a snapshot into a concrete Jotai atom. It does not fetch snapshots and does not subscribe to invalidation events — those concerns belong to the sync engine (@statesync/core).

Key difference from other adapters: Jotai stores state in individual atoms rather than a single store object. This adapter requires both a store reference AND the target atom. The store's get and set methods are used to read and write the atom's value. The adapter uses the updater form of store.set for atomic read-modify-write operations, avoiding race conditions between get and set.

Type Parameters

Type ParameterDefault typeDescription
State extends Record<string, unknown>-The shape of the atom's value (must be a plain object).
DataStateThe snapshot payload type. Defaults to State.
AtomunknownThe atom reference type.

Parameters

ParameterTypeDescription
storeJotaiStoreLike<State, Atom>The Jotai store (or any object satisfying JotaiStoreLike).
atomAtomThe target atom to apply snapshots into.
optionsJotaiSnapshotApplierOptions<State, Data>Configuration for apply mode, key filtering, data mapping, and strict validation.

Returns

SnapshotApplier<Data>

A SnapshotApplier whose apply method writes snapshot data into the Jotai atom.

Throws

When strict is true (the default) and toState returns a non-plain-object value.

Examples

ts
import { atom, createStore } from 'jotai/vanilla';
import { createJotaiSnapshotApplier } from '@statesync/jotai';
import { createRevisionSync } from '@statesync/core';

const store = createStore();
const profileAtom = atom({ name: '', email: '' });

const applier = createJotaiSnapshotApplier(store, profileAtom);

const sync = createRevisionSync({
  topic: 'user-profile',
  subscriber: mySubscriber,
  provider: mySnapshotProvider,
  applier,
});
ts
const applier = createJotaiSnapshotApplier(store, settingsAtom, {
  mode: 'replace',
  omitKeys: ['isMenuOpen'],
});
ts
interface ApiResponse { user: { name: string; email: string } }

const applier = createJotaiSnapshotApplier<ProfileState, ApiResponse>(
  store,
  profileAtom,
  { toState: (data) => data.user },
);

Released under the MIT License.