city-state-preact
v1.1.4
Published
Observable and encapsulated state management for Preact
Downloads
4
Readme
city-state-preact.js
Observable and encapsulated state management for Preact
Installation
npm install --save city-state-preact
Usage
<Subscribe>
component
Subscribes to an Observable (like a subscribable) and updates children whenever there is a new value.
//
// Model
//
import { Subscribe } from 'city-state-preact'
@subscribable
class Counter {
constructor() {
this._state = {
count: 0
}
}
increment() {
this._state.count += 1
}
decrement() {
this._state.count -= 1
}
}
const counter = new Counter()
//
// View
//
import React from 'react'
export default function CounterView({ counter }) {
<Subscribe to={[counter]}>
{(counterState => {
return <span>Counter: {counterState.counter}</span>
})}
</Subscribe>
}
Redux offers an Observable API that could be used with Subscribe
.
function CounterView({ reduxStore }) {
<Subscribe to=[reduxStore]>
{(currentState => {
return <span>Counter: {currentState.counter}</span>
})}
</Subscribe>
}
For a working example, see the code on /examples
@subscribable
Adds a minimal Observable interface to a class.
Interface:
this.state
: read-only instance statethis._state
: readable and writable state. Will be changed tothis.#state
once private properties reach stage 4this.subscribe()
: Observable subscribe methodthis[$$obseravble]
: Symbol.Observable interop point
import { subscribable } from 'city-state-preact';
@subscribable
class Counter {
constructor() {
this._state = { count: 0 }
}
increment() {
this._state.count += 1
}
decrement() {
this._state.count -= 1
}
}
const counter = new Counter()
counter.subscribe(() => {
console.log(counter.state.count)
}) // => 0
counter.increment() // => 1
counter.increment() // => 2
counter.decrement() // => 1
devtool()
Plot current state of a subscribable object (or any Observable) in Redux devtools.
@subscribable
class Foo {}
const foo = new Foo()
devtool(foo, { name: 'foo' })
Sponsor
If you found this library useful and are willing to donate, transfer some
bitcoins to 1BqqKiZA8Tq43CdukdBEwCdDD42jxuX9UY
.
Credits
caiogondim.com · GitHub @caiogondim · Twitter @caio_gondim