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-local

v1.0.7

Published

Tiny, simple, and robust technique for defining and acting with local states

Downloads

3,623,739

Readme

State · monthly downloads gitHub license Rate on Openbase build size npm version PRs welcome

:zap: Tiny, simple, and robust technique for defining and acting with local states (for all js environments - node, browser, etc.)

Synopsis

A local state for modules, functions, and other ECs

Motivation

We all love functional programming and the concepts of it. It gives us many clean patterns, which we use in our code regardless of exactly which paradigm is in the base of our codebase. But sometimes, for some reason, we can't keep our code "clean" and have to interact with items that are outside of the current lexical environment

For example:

:x:

let x = 0;
let y = 1;

// ...
function someFn() {
  // ...
  x++;
}

// ...
function anotherFn() {
 // ...
 y = 6;
 console.log(x);
}

// ...
function yetAnotherFn() {
  // ...
  y = x + 4;
  x = null; // 🚶
}

The example above lacks control over the mutations and consumption, which can lead to unpredictable and unwanted results. It is just an example of real-life usage and there are many similar cases that belong to the same class of the problem

The purpose of this library is to give an opportunity to work with local states in a clear, predictable, trackable, and strict way

:white_check_mark:

import state from 'state-local';

const [getState, setState] = state.create({ x: 0, y: 1 });

// ...
function someFn() {
  // ...
  setState(state => ({ x: state.x + 1 }));
}

// ...
function anotherFn() {
 // ...
 setState({ y: 6 });
 const state = getState();
 console.log(state);
}

// ...
function yetAnotherFn() {
  // ...
  setState(state => ({ y: state.x + 4, x: null }));
}

codesandbox

We also can track the changes in items:

import state from 'state-local';

const [getState, setState] = state.create({ x: 0, y: 1 }, {
  x: latestX => console.log('(⌐▀ ̯ʖ▀) Houston we have a problem; "x" has been changed. "x" now is:', latestX),
  y: latestY => console.log('(⌐▀ ̯ʖ▀) Houston we have a problem; "y" has been changed. "y" now is:', latestY),
});

// ...

codesandbox

We can use the subset of the state in some execution contexts:

import state from 'state-local';

const [getState, setState] = state.create({ x: 5, y: 7 });

// ...
function someFn() {
  const state = getState(({ x }) => ({ x }));

  console.log(state.x); // 5
  console.log(state.y); // ❌ undefined - there is no y
}

codesandbox

And much more...

Documentation

Contents

Installation

You can install this library as an npm package or download it from the CDN and use it in node or browser:

npm install state-local

or

yarn add state-local

or

<script src="https://unpkg.com/state-local/dist/state-local.js"></script>

<script>
// now it is available in `window` (window.state)
const [getState, setState] = state.create({ x: 11, y: 13 });
// ...
</script>

create

The default export has a method called create, which is supposed to be a function to create a state:

import state from 'state-local';

// state.create

// ...

codesandbox

create is a function with two parameters:

  1. initial state (required)
  2. handler (optional)

initial state

initial state is a base structure and a value for the state. It should be a non-empty object

import state from 'state-local';

/*
const [getState, setState] = state.create(); // ❌ error - initial state is required
const [getState, setState] = state.create(5); // ❌ error - initial state should be an object
const [getState, setState] = state.create({}); // ❌ error - initial state shouldn\'t be an empty object
*/

const [getState, setState] = state.create({ isLoading: false, payload: null }); // ✅
// ...

codesandbox

handler

handler is a second parameter for create function and it is optional. It is going to be a handler for state updates. Hence it can be either a function or an object.

  • If the handler is a function than it should be called immediately after every state update (with the latest state)
  • If the handler is an object than the keys of that object should be a subset of the state and the values should be called immediately after every update of the corresponding field in the state (with the latest value of the field)

see example below:

if handler is a function

import state from 'state-local';

const [getState, setState] = state.create({ x: 2, y: 3, z: 5 }, handleStateUpdate /* will be called immediately after every state update */);

function handleStateUpdate(latestState) {
  console.log('hey state has been updated; the new state is:', latestState); // { x: 7, y: 11, z: 13 }
}

setState({ x: 7, y: 11, z: 13 });
// ...

codesandbox

if handler is an object

import state from 'state-local';

const [getState, setState] = state.create({ x: 2, y: 3, z: 5 }, {
  x: handleXUpdate, // will be called immediately after every "x" update
  y: handleYUpdate, // will be called immediately after every "y" update
  // and we don't want to listen "z" updates 😔
});

function handleXUpdate(latestX) {
  console.log('(⌐▀ ̯ʖ▀) Houston we have a problem; "x" has been changed. "x" now is:', latestX); // ... "x" now is 7
}

function handleYUpdate(latestY) {
  console.log('(⌐▀ ̯ʖ▀) Houston we have a problem; "y" has been changed. "y" now is:', latestY); // ... "y" now is 11
}

setState({ x: 7, y: 11, z: 13 });
// ...

codesandbox

getState

getState is the first element of the pair returned by create function. It will return the current state or the subset of the current state depending on how it was called. It has an optional parameter selector

import state from "state-local";

const [getState, setState] = state.create({ p1: 509, p2: 521 });

const state = getState();
console.log(state.p1); // 509
console.log(state.p2); // 521

// or

const { p1, p2 } = getState();
console.log(p1); // 509
console.log(p2); // 521

codesandbox

selector

selector is a function that is supposed to be passed (optional) as an argument to getState. It receives the current state and returns a subset of the state

import state from 'state-local';

const [getState, setState] = state.create({ p1: 389, p2: 397, p3: 401 });

function someFn() {
  const state = getState(({ p1, p2 }) => ({ p1, p2 }));
  console.log(state.p1); // 389
  console.log(state.p2); // 397
  console.log(state.p3); // ❌ undefined - there is no p3
}

codesandbox

setState

setState is the second element of the pair returned by create function. It is going to receive an object as a change for the state. The change object will be shallow merged with the current state and the result will be the next state

NOTE: the change object can't contain a field that is not specified in the "initial" state

import state from 'state-local';

const [getState, setState] = state.create({ x:0, y: 0 });

setState({ z: 'some value' }); // ❌ error - it seams you want to change a field in the state which is not specified in the "initial" state

setState({ x: 11 }); // ✅ ok
setState({ y: 1 }); // ✅ ok
setState({ x: -11, y: 11 }); // ✅ ok

codesandbox

setState also can receive a function which will be called with the current state and it is supposed to return the change object

import state from 'state-local';

const [getState, setState] = state.create({ x:0, y: 0 });

setState(state => ({ x: state.x + 2 })); // ✅ ok
setState(state => ({ x: state.x - 11, y: state.y + 11 })); // ✅ ok

setState(state => ({ z: 'some value' })); // ❌ error - it seams you want to change a field in the state which is not specified in the "initial" state

codesandbox

License

MIT