1.1.4 • Published 6 years ago

city-state-preact v1.1.4

Weekly downloads
2
License
MIT
Repository
github
Last release
6 years ago

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 state
  • this._state: readable and writable state. Will be changed to this.#state once private properties reach stage 4
  • this.subscribe(): Observable subscribe method
  • this[$$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