Recall State
Simple reactive state factory.
Installation
npm install recall-state
Usage
Without proxies
import createState from 'recall-state'
// create state
const state = createState(1)
// pass function to state that will recalls each time state changes, returns { done } object
const listener1 = state((value, initial) => {
if (initial) {
console.log(`listener1 logs initial value: ${value}`)
} else {
console.log(`listener1 logs next value: ${value}`)
}
})
//> `listener1 logs initial value: 1`
const listener2 = state((value) => {
console.log(`listener2 logs ${value}`)
})
//> `listener2 logs 1`
state(2)
//> listener1 logs 2
//> listener2 logs 2
// call done method to remove listener from state
listener1.done()
state(3)
//> listener2 logs 3
listener2.done()
Using proxy methods
import createState from 'recall-state'
// create state
const state = createState(1, {
inc(value) {
value++
return value
},
dec(value) {
value--
return value
},
multiply(value, num) {
return value*num
}
})
// add listener
const listener = state((value, initial) => {
console.log(`listener logs ${value}`)
})
//> `listener logs 1`
state.inc()
//> listener logs 2
state.multiply(10)
//> listener logs 20
state.dec()
//> listener logs 19
listener.done() // terminating listener
Using proxy function
import createState from 'recall-state'
// create state
const state = createState(1, (action, payload) => {
if (action === 'INC') {
value++
return value
}
if (action === 'DEC') {
value--
return value
}
if (action === 'MULTIPLY') {
return value*payload
}
})
// add listener
const listener = state((value, initial) => {
console.log(`listener logs ${value}`)
})
//> `listener logs 1`
state('INC')
//> listener logs 2
state('MULTIPLY', 10)
//> listener logs 20
state('DEC')
//> listener logs 19
listener.done() // terminating listener