@kaiverse/signal
v0.3.1
Published
A simple reactive system for your Javascript application
Maintainers
Readme
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/signalpnpm add @kaiverse/signalVia jsr
deno add jsr:@kaiverse/signalnpx jsr add @kaiverse/signalpnpm dlx jsr add @kaiverse/signalVia CDN:
unpkg.com/@kaiverse/signalCompatibility
Signal is a Proxy object at its core, please check compatibility section.
Documentation
Example
🔗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] @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.
