Blog>
Snippets

Implementing Undo and Redo Features with TanStack Store

Code example showing how to implement undo and redo features in an application by leveraging the TanStack Store's snapshot functionality.
import { createStore } from '@tanstack/react-store';

const useStore = createStore({
  initialState: {
    history: [],
    currentIndex: -1
  },
  actions: {
    addToHistory: (state, snapshot) => {
      // Truncate any future states if any
      state.history = state.history.slice(0, state.currentIndex + 1);
      state.history.push(snapshot);
      state.currentIndex++;
    },
    undo: (state) => {
      if (state.currentIndex > 0) {
        state.currentIndex--;
      }
    },
    redo: (state) => {
      if (state.currentIndex < state.history.length - 1) {
        state.currentIndex++;
      }
    }
  }
});
This initializes the store with `history` for storing snapshots and `currentIndex` to keep track of the current state. Actions for `undo`, `redo`, and `addToHistory` are defined for managing the state history.
const snapshot = JSON.stringify(currentState);
useStore.actions.addToHistory(snapshot);
This snippet demonstrates how to take a snapshot of the current state (assuming `currentState` holds the current state of your application) and add it to the store's history for undo/redo functionality.
function undo() {
  useStore.actions.undo();
  const state = useStore.getState();
  const previousState = JSON.parse(state.history[state.currentIndex]);
  // Restore the application state to the previous one
}

function redo() {
  useStore.actions.redo();
  const state = useStore.getState();
  const nextState = JSON.parse(state.history[state.currentIndex]);
  // Restore the application state to the next one
}
These functions illustrate how to implement the undo and redo functionality using the store. They modify the `currentIndex` to point to the correct version of the application state in the history, and then restore the application state to that version.