snapshot
import { snapshot } from 'patronum';// orimport { snapshot } from 'patronum/snapshot';result = snapshot({ source, clock, fn })
Motivation
This method allows to copy any store on optional trigger unit. It useful when you want to save previous state of store before some actions.
Formulae
result = snapshot({ source, clock, fn });- Call
fnwith data fromsourcewhileclocktriggered, and create store with the value - If
fnreturnsundefined, the update will be skipped.
Arguments
source(Store) — Source store, data from this unit passed tofnclock(Event,Effect,Store) — Trigger unitfn((value: T) => U)— Transformation function
Returns
result(Store) — Copied store
Examples
Exact copy of store
import { createStore } from 'effector';import { snapshot } from 'patronum/snapshot';
const $original = createStore<string>('Example');
const $copy = snapshot({ source: $original });Exact copy on trigger
import { restore, createEvent } from 'effector';import { snapshot } from 'patronum/snapshot';
const changeText = createEvent<string>();const createSnapshot = createEvent();
const $original = restore(changeText, 'Example');
const $snapshot = snapshot({ source: $original, clock: createSnapshot,});
changeText('New text');
// $original -> Store with "New text"// $snapshot -> Store with "Example"
createSnapshot();
// $original -> Store with "New text"// $snapshot -> Store with "New text"Copy on trigger with transformation
import { restore, createEvent } from 'effector';import { snapshot } from 'patronum/snapshot';
const changeText = createEvent<string>();const createSnapshot = createEvent();
const $original = restore(changeText, 'Example');
const $lengthSnapshot = snapshot({ source: $original, clock: createSnapshot, fn: (text) => text.length,});
// $original -> Store with "Example"// $lengthSnapshot -> Store with 7 (length of "Example")
changeText('New long text');
// $original -> Store with "New long text"// $lengthSnapshot -> Store with 7 (length of "Example")
createSnapshot();
// $original -> Store with "New long text"// $lengthSnapshot -> Store with 13 (length of "New long text")