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

lipid

v2.0.1

Published

Simple state management using observables.

Downloads

43

Readme

Lipid

Simple state management using observables.

Install

# yarn
$ yarn add lipid
# NPM
$ npm install -S lipid

Setting up your state

Simple Example

Get started by instantiating the Lipid class:

import { Lipid } from 'lipid';
  
const myState = new Lipid();
console.log(myState.get());
// => {}

Each instantiated state is a separate instance of the Lipid class.

Default State

You can add a default state by passing in an object as the first argument:

import { Lipid } from 'lipid';

const myState = new Lipid({
  firstName: 'John',
  lastName: 'Doe',
  age: 5,
});

console.log(myState.get().name);
// => 'John'

Extend your state

You can extend the Lipid class with any sort of methods that you need:

import { Lipid } from 'lipid';

class MyState extends Lipid {
  isAdult() {
    return this.state.age >= 18;
  }
  hasLastName() {
    return !!this.state.lastName;
  }
}

const myState = new MyState({ age: 5 });
console.log(myState.isAdult());
// => false

API

set(state, [options])

Set state.

Args

  • state: Record<string, any> - next state.

  • options: { emit?: boolean, clear?: boolean } - options for setting state.

| Property | Description | Type | Default | |----------|----------------------------|--------|---------| | emit | Emit to subscribers | bool | true | | clear | Empty state before setting | bool | false |

Set state within your extending class, or with your instantiated instance:

inside your extended class:

import { Lipid } from 'lipid';

class MyState extends Lipid {
  updateName(name) {
    const fullName = name.split(' ');
    this.set({
      firstName: fullName[0],
      lastName: fullName[1],
    });
  }
}

const myState = new MyState();
myState.updateName('John Doe');

from the instantiated instance:

import myState from './my-state';

myState.set({
  firstName: 'John',
  lastName: 'Doe',
});

get(key?: string)

Get the entire state object with no arguments get(), or pass in a key to get one property get(key).

import { Lipid } from 'lipid';

const myState = new Lipid({ age: 29 });
myState.get(); // => { age: 29 }
myState.get('age'); // => 29

on(string[])

Lipid uses observables to emit events across your app. To create an observable you can subscribe to, call the .on() method.

If the props argument is empty (on() or on([])), all props changes will emit to this subscriber. You can also pass an array of strings to pick and choose what to listen to:

const myObservable = myState.on(['age']);

And listen for those changes:

myObservable.subscribe(({ state }) => {
  console.log(state.age);
  // only emits 'age' changes
});

revertToDefault(options: { emit?: true, clear?: true })

Revert state back to the default state passed in during instantiation.

import { Lipid } from 'lipid';

const myState = new Lipid({ age: 29 });
myState.set({ age: 32, show: true });
myState.reset();
myState.get(); // { age: 29 }

setDefault(State: Record<string, any>)

Set default state, so everytime you call revertToDefault() it will use this newly defined state. Note: This will not set state - you can follow up by firing revertToDefault().

import { Lipid } from 'lipid';

const myState = new Lipid({ age: 29 });
myState.set({ age: 32, show: true });
myState.setDefault({ age: 35, show: false });
myState.get(); // { age: 29 }

Internal state hooks

onSetBefore((currentState: Record<string, any>) => Record<string, any>

Manipulate state before set is called. Requires state to be returned.

Args

  • function(currentState, delta) => newState - function that returns new state.
class MyState extends Lipid {
  onSetBefore = (state) => {
    return {
      ...state,
      lastUpdated: new Date(),
    }
  }
}
const myState = new MyState();
myState.set({ age: 29 });
state.get();
// => { age: 29, lastUpdated: 1571291829316 }

onSetAfter(newState: Record<string, any>, delta: Record<string, any>)

Do side effect things after set is called.

Args

  • state - all of state.
  • delta - only the properties that were just changed.
class MyState extends Lipid {
  onSetAfter(state) {
    updateStorage('myState', state).then(() => {});
  }
}

Warning: calling this.set() within a hook will result in an infinite loop and will crash your app 😨. Don't do that.

lipidReactHookGenerator(LipidState)

This method will generate react hooks based off of changes made to your state.

import { Lipid, lipidReactHookGenerator } from 'lipid';

const myState = new Lipid({ message: 'Hello, world!' });
const useMyState = lipidReactHookGenerator(myState);

The generated hooks accept one argument: string[] - an array of property "keys" to watch for changes:

import { useMyState } from './my-state';

function myComponent() {
  const { message } = useMyState(['message']);
  return (
    <div>
      {message}
    </div>
  );
}