1.0.1 • Published 3 years ago

@utilityjs/use-memento-state v1.0.1

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

A React hook that keeps the track of the history of the state changes.

license npm latest package npm downloads types

npm i @utilityjs/use-memento-state | yarn add @utilityjs/use-memento-state

Usage

const MementoDemo = () => {
  const {
    state,
    setState,
    pastStates,
    futureStates,
    redo,
    undo,
    reset
  } = useMementoState(0);

  return (
    <React.Fragment>
      <button onClick={() => void setState(v => v + 1)}>Increase</button>
      <button onClick={() => void undo()}>Undo</button>
      <button onClick={() => void redo()}>Redo</button>
      <button onClick={() => void reset()}>Reset</button>
      <hr />
      <strong>History</strong>
      <ul>
        {pastStates.map(past => (
          <li style={{ color: "red" }} key={past}>
            {past}
          </li>
        ))}
        <li style={{ color: "#000", fontWeight: "bold" }}>
          {state}{" "}
          <span role="img" aria-label="Arrow">
            ⬅️
          </span>
        </li>
        {futureStates.map(future => (
          <li style={{ color: "green" }} key={future}>
            {future}
          </li>
        ))}
      </ul>
    </React.Fragment>
  );
};

API

useMementoState(initialPresent)

interface Mementos<T> {
  state: T;
  pastStates: T[];
  futureStates: T[];
  setState: React.Dispatch<React.SetStateAction<T>>;
  undo: () => void;
  redo: () => void;
  reset: () => void;
  hasPastState: () => boolean;
  hasFutureState: () => boolean;
}
declare const useMementoState: <T>(initialPresent: T) => Mementos<T>;

initialPresent

The value of the initial present state.