Blog>
Snippets

Saga for Capturing Previous State

Show how to create a saga that listens for specific actions and captures the previous state before the action is processed, storing it for future undo functionality.
import { takeEvery, select, put } from 'redux-saga/effects';
Imports necessary effects from redux-saga.
const selectCurrentState = state => state;
Selector to capture the current state before an action changes it.
function* savePreviousState(action) {
  const currentState = yield select(selectCurrentState);
  yield put({
    type: 'SAVE_STATE_FOR_UNDO',
    payload: currentState
  });
}
Saga worker to save the current state before specific actions.
function* watchActionsForUndo() {
  // Replace 'ACTION_TYPE' with the actions you want to track
  yield takeEvery('ACTION_TYPE', savePreviousState);
}
Saga watcher that listens for actions that should trigger saving the previous state.
export default watchActionsForUndo;
Exports the watch saga.