0.5.5 • Published 2 years ago
2680.js v0.5.5
2680
A simple & performant library for handling reactive state.
npm install 2680.js
Usage
To use 2680, simply import the state
function, and then use .set()
and .subscribe()
:
import { state } from "2680.js";
const count = state(0);
count.subscribe((value) => {
console.log("Count Changed:", value);
});
count.set(1); // Logs "Count Changed: 1"
count.set(2); // Logs "Count Changed: 2"
Set/Get
You can use .set()
and .get()
to manipulate the state:
const count = state(0);
count.set(1);
count.get(); // Returns 1
Subscribe
You can use .subscribe()
to add a listener to the state. This function will be called whenever the state changes:
const count = state(0);
count.subscribe((value) => {
console.log("Count Changed:", value);
});
count.set(1); // Logs "Count Changed: 1"
Asynchronous
You can also have asynchronous listeners:
const count = state(0);
count.subscribe(async (value) => {
console.log((await fetch("https://www.google.com/")).status);
console.log("Count Changed:", value);
});
count.set(1); // Outputs "200\nCount Changed: 1"
count.set(2); // Outputs "200\nCount Changed: 2"
Defer
You can deactivate a listener with .defer()
:
const count = state(0);
const logger = count.subscribe((value) => {
console.log("Count Changed:", value);
});
count.set(1); // Logs "Count Changed: 1"
logger.defer();
count.set(2); // Doesn't Log
Batch
You can use .batch()
to group together .set()
s, and only call the listener(s) at the end:
const count = state(0);
count.subscribe((value) => {
console.log("Count Changed:", value);
});
// Logs "Count Changed: 3"
count.batch(() => {
count.set(1);
count.set(count.get() + 2);
});
Proto
You can use .proto
to access array and object methods. If the method mutates the value, listeners will be called:
const count = state([0]);
count.subscribe((value) => {
console.log("Count Changed:", value);
});
count.proto.push(1); // Logs "Count Changed: [0, 1]"
count.proto.length = 3; // Logs "Count Changed: [0, 1, <1 empty item>]"
count.proto[2] = 2; // Logs "Count Changed: [0, 1, 2]"
count.proto.length; // Returns 3
const count = state({ count: 0 });
count.subscribe((value) => {
console.log("Count Changed:", value);
});
count.proto.hasOwnProperty("count"); // Returns true
count.proto.count = 6; // Logs "Count Changed: { count: 6 }"