Skip to content

Light wrapper around zustand to make state management in React easier

License

Notifications You must be signed in to change notification settings

StevenJPx2/staatshelfer

Repository files navigation

Staatshelfer

npm version npm downloads

This is a light wrapper over Zustand to provide max safety with the least compromise.

Have you found yourself defining the same "actions" or "functions" for certain variables over and over again?

Example:

type Store = {
  userId: string | undefined;
};

const useMainStore = create<Store>((set) => ({
  userId: undefined,
  setUserId: (userId: string | undefined) => set({ userId }),
}));

For every single new store item you create, you might have to create the same utility functions over and over again, making it less productive and laborious to maintain.

With Staatshelfer:

store.ts

import { defineStore, type StaatShelferStore } from "staatshelfer";

type Store = {
  userId: string | undefined;
};

const useMainStore = create<StaatShelferStore<Store>>((set) =>
  // throws an error if your definition for defaults don't match the Store type
  defineStore(set, {
    userId: undefined,
  }),
);

component.tsx

import { useMainStore } from "@/store";
import { selectFromStore } from "staatshelfer";

export function Component() {
  // selectFromStore selects all the relevant functions by default
  const { userId, setUserId, resetUserId } = selectFromStore(
    useMainStore,
    ["userId"], // this is auto-completed only with the main keys!
  );

  return;
}

Default functions

For non-array and array types:

  • setKey - function to set the key as a whole
  • resetKey - function to reset to the initially defined value.

For only array types:

  • pushToKey - to push an element to the key array.
  • unshiftToKey - to unshift an element to the key array.

Usage

Install package using your favorite package manager:

# pnpm
pnpm install staatshelfer zustand

Import:

// ESM
import {} from "staatshelfer";

// CommonJS
const {} = require("staatshelfer");

Development

  • Clone this repository
  • Install latest LTS version of Node.js
  • Enable Corepack using corepack enable
  • Install dependencies using pnpm install
  • Run interactive tests using pnpm dev

License

Made with 💛

Published under MIT License.

About

Light wrapper around zustand to make state management in React easier

Resources

License

Stars

Watchers

Forks

Packages

No packages published