0.0.13 • Published 2 years ago

react-stable-state v0.0.13

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

react-stable-state

test Coverage Status

A simple React Hooks for stable useState.

This module was designed with the use case of saving data after a certain amount of time has elapsed after editing. By using useStableState instead of useState, the number of times to process can be greatly reduced.

You can check a demo page here.

Installation

yarn add react-stable-state

or

npm i --save react-stable-state

Example

Example of saving to Local Storage after the value is changed and a certain period of time has elapsed.

import { useEffect } from "react";
import { useStableState } from "react-stable-state";

const App = () => {
  const [value, stableValue, setValue] = useStableState<string>({
    initialState: localStorage.getItem("key") || "",
  });

  useEffect(() => {
    console.log("stable value has changed!");
    localStorage.setItem("key", stableValue);
  }, [stableValue]);

  return (
    <div className="App" id="app">
      <input
        type="text"
        id="text-input"
        value={value}
        onChange={(e) => {
          e.preventDefault();
          setValue(e.target.value);
        }}
      ></input>
    </div>
  );
};
export default App;

You can also store values to server by calling the Fetch API in the onStableStateChanged callback function. onStableStateChanged callback would not invoked when the state is changed by the load function

import { useStableState } from "react-stable-state";

const App = () => {
  const [value, stableValue, setValue] = useStableState<string>({
    initialState: "",
    load: () =>
      fetch("/data_store").then((resp) => resp.text()),
    onStableStateChanged: () =>
      fetch("/data_store", {
        method: "POST",
        body: JSON.stringify({ value: stableValue }),
        headers: {
          "Content-Type": "application/json",
        },
      }).then(),
  });

  return (
    <div className="App" id="app">
      <input
        type="text"
        id="text-input"
        value={value}
        onChange={(e) => {
          e.preventDefault();
          setValue(e.target.value);
        }}
      ></input>
    </div>
  );
};
export default App;
0.0.13

2 years ago

0.0.12

2 years ago

0.0.11

2 years ago

0.0.10

2 years ago

0.0.9

2 years ago

0.0.8

2 years ago

0.0.7

2 years ago

0.0.6

2 years ago

0.0.5

2 years ago

0.0.4

2 years ago

0.0.3

2 years ago

0.0.2

2 years ago

0.0.1

2 years ago