iaktta
v0.2.7
Published
state management
Downloads
8
Readme
iaktta
A small observable state container
I would recommend you stick to the more popular state management libraries.
Installing
npm install iaktta
Example
import { observable, createObserverHook } from 'iaktta';
import { h, render } from 'preact';
import { useState, useEffect } from 'preact/hooks';
const useObserver = createObserverHook(useState, useEffect);
const model = observable({ counter: 0 });
const increment = () => model.counter ++;
const decrement = () => model.counter --;
const Counter = () => useObserver(() => (
<div>
<button onClick={decrement}>-</button>
<strong>{model.counter}</strong>
<button onClick={increment}>+</button>
</div>
));
render(<Counter />, document.body);
Size
Public functions
observable
The observable
function creates a new observable object.
When a property of this object is accessed or modified, its observers are notified.
import { observable } from 'iaktta';
const model = observable({ counter: 0 });
const inc = () => model.counter ++;
// also works with decorator syntax for class properties
class Model {
@observable counter = 0;
inc: () => { this.counter++; }
}
createObserverHook
createObserverHook
is a function that creates a react/preact hook to create observers. it takes 'useState' and 'useEffect' parameters to be used.
import { observable, createObserverHook } from 'iaktta';
import { render, h } from 'preact';
import { useState, useEffect } from 'preact/hooks';
const useObserver = createObserverHook(useState, useEffect);
const model = observable({ counter: 0 });
const inc = () => model.counter ++;
const Example = () => useObserver(() => <div onClick={inc}>The count is {model.counter}</div>);
render(<Example />, document.body);
computed
A computed value caches the result of a potentially heavy operation, only re-running it if the underlying values have changed.
import { observable, computed } from 'iaktta';
const model = observable({ value: 100 });
const randomValue = computed(() => (Math.random() * model.value) | 0);
console.log(randomValue()); // 13
console.log(randomValue()); // 13
console.log(randomValue()); // 13
model.value = 200;
console.log(randomValue()); // 163
// also works with decorator syntax for class properties
class Model {
@observable value = 100;
@computed get randomValue() {
return (Math.random() * this.value) | 0;
}
}
run
The run
function is a convenience function that will automatically run a function every time an observable watched by it changes. It returns a function that can be used to stop the automatic update.
import { run, observable } from 'iaktta';
const model = observable({ value: 100 });
// this will console log "value set to 100"
const cancel = run(() => {
console.log('value set to ' + model.value);
});
// this will console log "value set to 200"
model.value = 200;
// cancel future invocations
cancel();
// this will not console log
model.value = 300;