0.3.1 • Published 10 months ago

@kaiverse/signal v0.3.1

Weekly downloads
-
License
MIT
Repository
github
Last release
10 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 jsr:@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());
});

Frameworks compatibility

This package is built for vanilla JS/TS applications.

However, below are implementations to adapt with some frameworks's reactive systems.

React Server Components & Functions

Compatible.

React

Use this package instead: Experimental(https://jsr.io/@kaiverse/signal-react)

Astro

Compatible. No additional setup required.

You can use it in the component script section for server signals, and/or the <script> tag for client signals.

SolidJS, VueJS

... Just use their "signals" APIs.

0.3.0

10 months ago

0.3.1

10 months ago

0.2.3

12 months ago

0.2.2

1 year ago

0.2.1

1 year ago

0.2.0

1 year ago