Giter Club home page Giter Club logo

haversack's Introduction

Haversack

NPM version NPM downloads MIT License

Easy save state management using browser localStorage or sessionStorage and React Hooks.

  • Written in TypeScript πŸŽ‰
  • Offers React hooks for both localStorage and sessionStorage 🎣
  • Set simple key/value pairs or an immutable JSON structure
  • JSON state merging
  • Event handling to sync state between browser tabs
  • SSR friendly, Next.js compatible
  • Small and performant (no dependencies, 732B Minified + gzipped) ⚑️

sessionStorage is an underrepresented feature as most libraries don't support using either API interchangeably. Storing data to the session is more secure, and is perfectly suitable for many use-cases. Learn about the difference on MDN!

Installation

Install with NPM or Yarn:

npm install --save haversack
yarn add haversack

Usage With React

Haversack exports the two following React hooks, depending on whether you want to use localStorage or sessionStorage:

import { useLocalStorage, useSessionStorage } from 'haversack';

Get and Set

Each hook returns an object with the current stored value and a function to update the stored value.

JavaScript

function MyComponent() {
  const { value, setValue } = useLocalStorage('myKey');

  useEffect(() => {
    // update the stored value after mount
    setValue('updatedValue');
  }, []);

  return <div>The stored value is {value}</div>;
}

TypeScript

By passing a TypeScript type to the hook, you can enforce a consistent typing for the stored value.

function MyComponent() {
  const { value, setValue } = useLocalStorage<string>(
    'myKey',
  );

  useEffect(() => {
    setValue('updatedValue'); // TS is happy πŸ‘
    setValue(5); // TS is unhappy πŸ‘Ž
  }, []);

  return <div>The stored value is {value}</div>;
}

Default Value

You can pass an optional default value to the hook. This value will be returned if setValue has not been called yet.

const defaultValue = 'bar';

function MyComponent() {
  const { value } = useLocalStorage('foo', defaultValue);

  return (
    <div>
      The stored value is {value}, but is {defaultValue} by default
    </div>
  );
}

See notes on SSR compatibility for the server-side behavior of the default value.

Versioning and Cache Busting

You can pass an optional number or string to the hook to apply a specific version to your stored data. If the structure of your data changes, users who have stored data from the previous structure can experience issues when the incompatible data is applied to the new structure. Think of the version param as a schema version for the data.

const schemaVersion = 2;

function MyComponent() {
  const { value } = useLocalStorage('foo', 'bar', schemaVersion);

  return (
    <div>
      The stored value is {value} for version {schemaVersion}. If the user had
      data stored with a different schema version, that old data will be
      invalidated.
    </div>
  );
}

There is no enforcement of standards on the versionβ€”Haversack will do a simple === equality check to determine if the version has changed. Any change in version number, forward or backward, will cause the stored data to be deleted to await new data with the current version number. If previous data was stored without a version number, the data will be invalidated when a version number is introduced.

Using a string for the version is especially useful if you want to create a hash of a data set to dynamically determine whether or not to invalidate the cache.

Reset the Stored Value

To remove the value from storage, call the resetValue function. This will return the value to the default if supplied or undefined if not.

function MyComponent() {
  const { value, resetValue } = useLocalStorage('myKey');

  return <button onClick={resetValue}>Reset value</button>;
}

Merging State

A unique feature of the library is the ability to manage an immutable store that you can easily merge with updated values.

interface Settings {
  name: string;
  currentHp: number;
  spells?: string[];
}

function MyComponent() {
  const {
    value: settings,
    setValue: writeSettings,
    mergeState: updateSettings
  } = useLocalStorage<Settings>(
    'appSettings',
  );

  useEffect(() => {
    // set the initial state
    writeSettings({
      name: 'Jan Darkmagic',
      currentHP: 12,
    });
  }, []);

  const fullRest = () => {
    // will not affect the `name` setting
    updateSettings({
      currentHP: 34, // updates existing field
      spells: ['Burning Hands', 'Charm Person'], // adds new field
    });
  }

  return (
    <>
      <div>User name: {settings.name}</div>
      <button onClick={() => fullRest()}>
        Full rest
      </button>
    </>
  );
}

Timestamps

The hooks always return a timestamp of when the stored value was most recently updated as a JavaScript Date object.

function MyComponent() {
  const { value, timestamp } = useLocalStorage('myKey');

  return (
    <>
      <div>The stored value is {value}</div>
      <div>It was updated at: {timestamp.toString()}</div>
    </>
  );
}

Storage Event Sync

Each time you implement a Haversack hook, a storage event handler is registered. Any instance of your component on alternate browser tabs will be notified that localStorage has changed, and update the value accordingly.

Notes on Server-Side Rendering Compatibility

Obviously browser storage APIs are not functional on the server, and this library is not designed to persist data between the two sources. However, Haversack is built to be friendly with server-side rendered environments including Next.js. If you try to access a stored value on the server, it will return the default value or undefined if a default is not specified. You should note that if you are rendering the value as text in a React component, this can throw a warning since the server rendered page will mismatch the hydrated client-side render.

If you need functionality to pass state between client and server, you will need something more complex like Redux state management with the Redux Persist library, or an external database.

Known Issues

Placing the haversack inside an extradimensional space created by a bag of holding, portable hole, or similar item instantly destroys both items and opens a gate to the Astral Plane. The gate originates where the one item was placed inside the other. Any creature within 10 feet of the gate is sucked through it and deposited in a random location on the Astral Plane. The gate then closes. The gate is one-way only and can't be reopened.

haversack's People

Contributors

colinhemphill avatar renovate-bot avatar renovate[bot] avatar

Watchers

 avatar  avatar

Forkers

agentmishra

haversack's Issues

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • Update dependency eslint to v8.57.0
  • Update dependency eslint-config-prettier to v9.1.0
  • Update dependency typescript to v5.4.5
  • Update dependency eslint to v9
  • Update dependency husky to v9
  • Update typescript-eslint monorepo to v7 (major) (@typescript-eslint/eslint-plugin, @typescript-eslint/parser)
  • πŸ” Create all rate-limited PRs at once πŸ”

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/main.yml
  • actions/checkout v4
  • mattallty/jest-github-action v1
npm
package.json
  • @swc/core 1.3.83
  • @testing-library/react-hooks 8.0.1
  • @types/jest 29.5.4
  • @types/react 17.0.65
  • @typescript-eslint/eslint-plugin 6.6.0
  • @typescript-eslint/parser 6.6.0
  • eslint 8.48.0
  • eslint-config-prettier 9.0.0
  • eslint-plugin-prettier 5.0.0
  • eslint-plugin-react-hooks 4.6.0
  • husky 8.0.3
  • jest 29.6.4
  • jest-environment-jsdom 29.6.4
  • jest-localstorage-mock 2.4.26
  • lint-staged 14.0.1
  • mockdate 3.0.5
  • prettier 3.0.3
  • react 17.0.2
  • react-test-renderer 17.0.2
  • ts-jest 29.1.1
  • tsup 7.2.0
  • typescript 5.2.2
  • react >=16.8.0

  • Check this box to trigger a request for Renovate to run again on this repository

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.