Skip to content

PrettyCoffee/yaasl

Repository files navigation

yaasl - yet another atomic store library

license NPM Version NPM Downloads minzipped size

This project is meant for personal use. I won't stop you from using it, but I would rather recommend to use a similar and more mature solution like jotai.

See the docs for detailed documentation.

Installation

You can install a yaasl package like you would do with any other:

npm i @yaasl/<package>

Available packages:

Name Description
@yaasl/core Core package for vanilla JS.
@yaasl/devtools Adapter to use redux browser devtools
@yaasl/react React bindings for yaasl.
@yaasl/preact Preact bindings for yaasl.

Quickstart

  1. Pick one of the main packages
npm i @yaasl/core
npm i @yaasl/react
npm i @yaasl/preact
  1. Create an atom
import { createAtom } from "@yaasl/core";

const myAtom = createAtom({ defaultValue: 0 });
  1. Use the atom
// Read
const currentValue = myAtom.get(atom);
// Write
myAtom.set(nextValue);
// Subscribe to changes
myAtom.subscribe((value) => {
  console.log(value);
});

Usage examples

Vanilla typescript

import { createAtom, CONFIG, localStorage } from "@yaasl/core";

// Provide an app name to yaasl
CONFIG.name = "demo-vanilla";

// Create a counter atom that is connected to the local storage
const counter = createAtom({
  name: "counter", // local storage key will be "demo-vanilla/counter"
  defaultValue: 0,
  effects: [localStorage()],
});

const setupCounter = (element: HTMLButtonElement) => {
  const updateCounterText = (value: number) =>
    (element.innerHTML = `count is ${value}`);

  element.addEventListener("click", () => {
    // Set the value of the atom
    counter.set((previous) => previous + 1);
  });

  // Subscribe to value changes
  counter.subscribe((value) => updateCounterText(value));

  // Read the value of the atom in the store
  updateCounterText(counter.get());
};

const counter = document.getElementById("counter");
setupCounter(counter);

React (or Preact)

import { createAtom, CONFIG, localStorage, useAtom } from "@yaasl/react"; // or "@yaasl/preact"

// Provide an app name to yaasl
CONFIG.name = "demo-react";

// Create a counter atom that is connected to the local storage
const counter = createAtom({
  name: "counter", // local storage key will be "demo-react/counter"
  defaultValue: 0,
  effects: [localStorage()],
});

export const Counter = () => {
  // Use the atom like you would use a state
  const [value, setValue] = useAtom(counter);

  const onClick = () => setValue((previous) => previous + 1);

  return <button onClick={onClick}>count is {value}</button>;
};