0.2.3 • Published 9 months ago

@kaiverse/signal v0.2.3

Weekly downloads
-
License
MIT
Repository
github
Last release
9 months ago

.github/workflows/ci.yml

This package draws strong inspiration from KnockoutJS's concepts and SolidJS's Signal, enabling us to use Signals in vanilla JavaScript. JS Signals proposal is currently in Stage 1.

Installation

Via npmjs

npm i @kaiverse/signal
pnpm add @kaiverse/signal

Via jsr

deno add @kaiverse/signal
npx jsr add @kaiverse/signal
pnpm dlx jsr add @kaiverse/signal

Via CDN:

unpkg.com/@kaiverse/signal

Compatibility

Signal is a Proxy object at its core, please check compatibility section.

Documentation

Functions & Types

Example

Playground source code

🔗Signal Proxy

/**
 * ```html
 * <p id="fetch-result"></p>
 * <button type="button" onclick="fetchNextUser()">Get next user</button>
 * ```
 */

import {signalProxy} from '@kaiverse/signal';

const resultElement = document.getElementById('fetch-result');

const userSignal = signalProxy({userId: 123, reqCount: 0}, async (key, newValue) => {
  // Do something when any userSignal's prop value changes
  console.log(`[userSignal updated] key: ${key}, value: ${newValue}`);

  if (key === 'userId') {
    // Do something on `userId` changes only
    const userId = newValue;
    const response = await fetch(`${basePath}/user/${userId}`);
    const userData = await response.json();
    const totalReqCount = userSignal.reqCount + 1;
    userSignal.reqCount = totalReqCount;

    if (resultElement)
      resultElement.innerHTML = `Name: ${userData.name}<br/>Total requests: ${totalReqCount}`;
  }
});

function fetchNextUser() {
  userSignal.userId++;
}

🚦Signal utilities

If you have experience with SolidJS or ReactJS, you'll find these utility functions very familiar.

import {createComputed, createEffect, createSignal} from '@kaiverse/signal';

const [count, setCount] = createSignal(0);

setInterval(() => {
  setCount((c) => c + 1); // or setCount(count() + 1)
}, 1000);

createEffect(() => {
  // log the count signal's value to the console every 1 second
  console.log('count =', count());
});

const doubled = createComputed(() => count() * 2);

createEffect(() => {
  console.log('[computed] doubled =', doubled());
});

Framework ports?

React

React signal hooks implementation. Experimental. DO NOT use in production.

Those hooks work, but its lack of testing and seems that the usage of memory is inefficient. An alternative approach may be better. Please feel free to open PRs. Your contributions are welcomed and appreciated.

React playground (codesandbox) - source code

0.2.3

9 months ago

0.2.2

11 months ago

0.2.1

11 months ago

0.2.0

11 months ago