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

@yanfoo/react-var

v2.2.0

Published

Reactive variables for React

Downloads

29

Readme

Reactive variables npm (scoped) Socket Badge

Observable global state management for React. This project was inspired by jorbuedo's react-reactive-var.

Install

npm i @yanfoo/react-var --save
yarn add @yanfoo/react-var
pnpm i @yanfoo/react-var

Usage

// auth.ts
/*
   This is the context wrapping the global state and exposing a contained API
*/
import reactVar from "@yanfoo/react-var";
//    or
// import { createReactVar } from '@yanfoo/react-var';

type User = {
  id: number;
  username: string;
};

type UserAuthStatus = {
  user: User | null;
  error: string | null;
};

// default comparator is equality : a === b
export const activeUser = reactVar<UserAuthStatus>(
  { user: null, error: null },
  {
    comparator: (a, b) => a.user?.id === b.user?.id && a.error === b.error,
  }
);

// the API
export const authenticator = {
  login: (username: string, password: string): void => {
    // we simulate a network delay...
    setTimeout(() => {
      if (password === "1234") {
        activeUser({ user: { id: 1, username }, error: null }); // simulate a successful login
      } else {
        activeUser(({ user }) => ({
          user,
          error: "Invalid username or password",
        }));
      }
    }, 200); // 200ms
  },
  logout: () => {
    activeUser({ user: null, error: null }); // again, this could be asynchronous
  },
};
// Component.tsx
/*
   This is the component making use of the global state and API
*/
import React from "react";
import { authenticator, activeUser } from "./auth";

export default () => {
  const userRef = React.useRef<HTMLInputElement>(null);
  const passRef = React.useRef<HTMLInputElement>(null);

  const handleLogin = () =>
    authenticator.login(userRef.current?.value, passRef.current?.value);

  return (
    <div>
      <div>
        Currently authenticated user : <UserLabel />
      </div>
      <AuthMessage />
      <div>
        <label for="username">Username</label>
        <input id="username" type="text" ref={userRef} />
      </div>
      <div>
        <label for="username">Password</label>
        <input id="username" type="password" ref={passRef} />
      </div>
      <div>
        <button onClick={handleLogin}>Login</button>
      </div>
    </div>
  );
};

const UserLabel = () => {
  const username = activeUser.useValue(({ user }) => user?.username ?? null);
  //    ^?:string | null

  return username ?? "Guest";
};

const AuthMessage = () => {
  const message = activeUser.useValue(({ error }) => error ?? null);
  //    ^?:string | null

  return message ? <div>{message}</div> : null;
};

Limitations

Setting a new values to a ReactVar can be made asynchronously. Meaning that any modification will cause parallel modifications to be stacked and processed sequentially. However, trying to modify a ReactVar within a subscriber callback will fail, and this is in order to prevent race conditions, where the subscriber and the setter would wait for each other to complete, creating a dead lock situation.

Example

const myVar = reactVar();

myVar.subscribe(({ value }) => {
  myVar(value + 1);
  // Error: Cannot modify ReactVar while it is already being modified!
});

myVar(0);

Workaround

The subscription handler provides an after function to invoke a callback when the mutation has settled. This callback is called asynchronously, and allows to immediately modify the ReactVar instance. If used, this feature should include an exit condition as it will trigger updates as long as the value is evaluated as different by the comparator; using this feature should be avoided if possible.

const myVar = reactVar(0, {
  comparator: (a, b) => Math.abs(a - b) < 0.5,
});

myVar.subscribe(({ value, after }) => {
  // execute this once every changes have settled
  after(() => {
    myVar(myVar.value / 2);
  });
});

myVar(16);
// Will update myVar with the following values until definitely settled:
//    16, 8, 4, 2, 1, 0.5
// After everything is settled, myVar.value = 0.25 because the comparator
// consider equal any value below 0.5

Contribution

All contributions welcome! Every PR must be accompanied by their associated unit tests!

License

MIT