npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

use-revisioned-state

v1.0.1

Published

Revisioned state manaement in React

Downloads

2

Readme

use-revisioned-state

React hook for keeping the state revisioned and revertable as same as git do. It stores not the whole copy, only the diff of changes.

Example

import useRevisionedState from "use-revisioned-state";

type AppState = {
  users: string[];
  viewsCount: number;
};
function App() {
  const [appState, setAppState, history, revert] = useRevisionedState<AppState>({
    users: ["fatih"],
    viewsCount: 0,
  });

  return (
    <div>
      <button onClick={() => setState({ ...appState, viewsCount: 1 })}>
        increase
      </button>
    </div>
  );
}

After the button click, the history will be:

[
  {
    "hasChange": true,
    "changed": [["viewCount", 1, 0]],
    "added": [],
    "removed": []
  }
]

The changed value "viewCount" will be in the "changed" key with the previous value. The added and removed keys stand for Array and Object keys.

import useRevisionedState from "use-revisioned-state";

type AppState = {
  users: string[];
  viewsCount: number;
};
function App() {
  const [appState, setAppState, history, revert] = useRevisionedState({
    users: ["fatih"],
    viewsCount: 0,
  });

  return (
    <div>
      <button
        onClick={() =>
          setState({ ...appState, viewsCount: 0, users: ["fatih", "sarah"] })
        }
      >
        add user
      </button>
    </div>
  );
}

The change log will be:

[ {
  "hasChange": true,
  "changed": [],
  "added": [ [ "users.1", "sarah" ] ],
  "removed": []
}, ] `

The ChangeLog type looks like:

export type ChangeLog<S> = {
  hasChange: boolean;
  added: [path: string, value: any][];
  removed: [path: string, value: any][];
  changed: [path: string, value: any, previousValue?: any][];
  updated?: [value: S, previousValue: S];
};

The path of the changed value is separated by "." dot. users.0.name corresponds to the users[0].name.

Reverting the history

useRevisionedState hooks returns with the history collection and revert function.

function App() {
  const [appState, setAppState, history, revert] = useRevisionedState({
    users: ["fatih"],
    viewsCount: 0,
  });

  return (
    <div>
      <button
        onClick={() =>
          setState({ ...appState, viewsCount: 0, users: ["fatih", "sarah"] })
        }
      >
        add user
      </button>
      <button
        onClick={() =>
          revert(history[history.length - 1]);
        }
      >
        undo
      </button>
    </div>
  );
}

You can undo the last change by reverting the last change. It will create an another change log.

If you want to revert the whole state, you need to reverse the history and pass it to the revert function.

<button
  onClick={() =>
    const back = [...history];
    back.reverse();
    revert(back);
  }
>
  Revert all changes
</button>

If you want to do the redo, you can count the undo click of user, and slice the history with that number and pass it to the revert function.

Implementing an Undo-Redo

For each Undo and Redo action, you need to go to the history twice as user clicked to the back or redo button, because revert function also writes to the history as same as git cherry-pick.


import useRevisionedState from "use-revisioned-state";
import { useState } from "react";

function App() {
  const [appState, setAppState, history, revert] = useRevisionedState({
    users: [],
    viewCount: 1,
  });

  const [clickedUndoCount, setClickedUndoCount] = useState(0);
  const [clickedRedoCount, setClickedRedoCount] = useState(0);

  return (
    <div className="App">
      {appState.viewCount}
      <br />
      <button
        onClick={() => {
          setClickedUndoCount(0);
          setAppState({ ...appState, viewCount: appState.viewCount + 1 });
        }}
      >
        Increase
      </button>
      <button
        onClick={() => {
          setClickedUndoCount(clickedUndoCount + 1);
          revert([
            history[history.length - 1 - clickedUndoCount * 2],
          ]);
        }}
      >
        Undo
      </button>
      <button
        disabled={clickedUndoCount === 0 || clickedUndoCount === clickedRedoCount}
        onClick={() => {
          const back = history[history.length - 1 - clickedRedoCount * 2];
          revert([back]);
          setClickedRedoCount(clickedRedoCount + 1);
        }}
      >
        Redo
      </button>
      <button
        onClick={() => {
          setClickedRedoCount(0);
          setClickedUndoCount(0);
          const back = [...history];
          back.reverse();
          revert(back);
        }}
      >
        Revert all history
      </button>
      <br />
      <h3>The change log</h3>
      {history.map((item) => (
        <pre>{JSON.stringify(item, null, 4)}</pre>
      ))}
    </div>
  );
}