0Pricing
Sveltejs Academy · Lesson

Undo/Redo with Store History

Build a history stack around a writable store to support undo and redo.

History Stack

Wrap a writable store with past/present/future arrays to support undo/redo.

Basic Implementation

Maintain a list of previous states.

function createHistory(initial) {
  let past = [], future = [];
  const state = writable(initial);
  return {
    subscribe: state.subscribe,
    set(v) { past.push(get(state)); future = []; state.set(v); },
    undo() { if (past.length) { future.push(get(state)); state.set(past.pop()); } },
    redo() { if (future.length) { past.push(get(state)); state.set(future.pop()); } }
  };
}

All lessons in this course

  1. Store Architecture: Feature Modules
  2. Event Bus Pattern with Stores
  3. Optimistic UI Updates
  4. Undo/Redo with Store History
← Back to Sveltejs Academy