0.1.1 • Published 3 years ago

use-undoable-reducer v0.1.1

Weekly downloads
-
License
MIT
Repository
-
Last release
3 years ago

use-undoable-reducer

A react hook to add undo and redo history to a reducer from useReducer.

Installation

Using yarn

yarn add use-undoable-reducer

Using npm

npm install use-undoable-reducer

Basic Usage

import React from 'react';
import { useUndoableReducer } from 'use-undoable-reducer';

export function MyApp() {
  const {
    state,
    dispatch,
    canRedo,
    canUndo,
    triggerRedo,
    triggerUndo,
  } = useUndoableReducer(reducer, initialState);

  return (
    <div>
      <button disabled={!canUndo} onClick={triggerUndo}>
        Undo
      </button>
      <button disabled={!canRedo} onClick={triggerRedo}>
        Redo
      </button>
    </div>
  );
}
PropertyTypeDescription
stateobjectCurrent state object.
dispatchfunctionDispatcher function returned from useReducer
canRedobooleanIndicates if there are any contents in the history stack that can be restored.
canUndobooleanIndicates if there are any contents in the history stack.
triggerRedofunctionRedo the previous action.
triggerUndofunctionUndo the previous action.

Options

import { useUndoableReducer, excludeActionTypes } from 'use-undoable-reducer';

const {
  state,
  dispatch,
  canRedo,
  canUndo,
  triggerRedo,
  triggerUndo,
} = useUndoableReducer(reducer, initialState, {
  maxHistory: 10,
  filterActionTypes: excludeActionTypes(['my_action_to_ignore']),
  ignoreInitialState: true,
});
OptionTypeDefaultDescription
maxHistorynumber20The maximum number of items to keep in undo history.
filterActionTypesfunctionundefinedActions to be ignored from undo history.
ignoreInitialStatebooleanundefinedIgnore the first state update and don't add to history.

excludeActionTypes

excludeActionTypes is a helper function exposed to be used with filterActionTypes. You can pass in an array of actions that you want to be ignored from undo history.

Type signature:

excludeActionTypes(actions: Array<string>) => void;