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

state-guard

v5.2.0

Published

Type-safe, deterministic state management featuring state machines and automatic stale snapshot invalidation.

Downloads

56

Readme

StateGuard

Type-safe, deterministic state management featuring state machines and automatic stale snapshot invalidation.

StateGuard is a JavaScript library for managing state with an emphasis on type safety, enabling seamless integration with TypeScript. It facilitates deterministic behavior by offering an encapsulated state machine, user-defined actions and state transformers, as well as automatic stale snapshot invalidation.

✅ 536 B with all dependencies, minified and gzipped.

Installation

npm install state-guard

Usage Example

Here's how to use StateGuard to define a simple state machine for fetching website content:

  1. Import createMachine function from the StateGuard package.
import { createMachine } from 'state-guard';
  1. Create a websiteContent machine using the createMachine function, with the initial state, value, a transformer map, and transitions map.
const websiteContent = createMachine({
  initialState: `resetted`,
  initialValue: undefined,

  transformerMap: {
    resetted: () => undefined,
    fetching: (url: string) => ({ url }),
    resolved: (text: string) => ({ text }),
    rejected: (error: unknown) => ({ error }),
  },

  transitionsMap: {
    resetted: { fetch: `fetching` },
    fetching: { resolve: `resolved`, reject: `rejected` },
    resolved: { reset: `resetted` },
    rejected: { reset: `resetted` },
  },
});
  1. Subscribe to websiteContent to start fetching if in the fetching state.
websiteContent.subscribe(async () => {
  const fetching = websiteContent.get(`fetching`);

  if (fetching) {
    try {
      const response = await fetch(fetching.value.url);
      const text = await response.text();

      if (fetching.isFresh()) {
        fetching.actions.resolve(text);
      }
    } catch (error) {
      if (fetching.isFresh()) {
        fetching.actions.reject(error);
      }
    }
  }
});
  1. Subscribe to websiteContent to log the current state and value.
websiteContent.subscribe(() => {
  const { state, value } = websiteContent.get();

  console.log(state, value);
});
  1. Trigger the fetch action in the resetted state.
websiteContent.assert(`resetted`).actions.fetch(`https://example.com`);
  1. Implement a React component using the useSyncExternalStore hook for state synchronization.
import * as React from 'react';

const YourComponent = () => {
  const websiteContentSnapshot = React.useSyncExternalStore(websiteContent.subscribe, () =>
    websiteContent.get(),
  );

  // Your component logic and rendering.
};

Ensuring Snapshot Freshness

In some cases, a snapshot taken can become stale, for example, when used after the result of an asynchronous operation. Using a stale snapshot will lead to exceptions being thrown, and it is crucial to ensure that this does not happen. The StateGuard API enables you to avoid such issues by allowing you to check the freshness of a snapshot or get an updated one before proceeding.

Avoiding State Transitions in Subscription Listeners

Performing state transitions directly within a subscription listener is prohibited in StateGuard. Using actions to change the state within a listener will lead to exceptions being thrown. This enforcement helps prevent cascading updates, exponential state changes, and potential violation of the unidirectional data flow principle.