1.1.1 • Published 6 years ago

centralpark v1.1.1

Weekly downloads
1
License
MIT
Repository
-
Last release
6 years ago

centralpark

A centralized state container that uses Web Worker.

Installation

This module is distributed via npm which is bundled with node and should be installed as one of your project's dependencies:

npm install --save centralpark

If you're using Webpack, you will need worker loader as well:

npm install --save worker-loader

Usage

  1. First create a worker for the store.
import { createStore } from "centralpark";

createStore({ counter: 0 }, (command, _data, state) => {
  switch (command) {
    case "increment": {
      const newState = {
        ...state,
        counter: state.counter + 1,
      };

      return newState;
    }
    default: {
      return state;
    }
  }
});
  1. Initialize the worker in the main thread.
import { h, render } from "preact";
import { Provider } from "centralpark/preact";
import App from "path/to/App";
import Store from "worker-loader!path/to/store";

const node = document.getElementById("index");
const store = new Store();

render(
  <Provider store={store}>
    <App />
  </Provider>,
  node,
  node.firstElementChild
);
  1. Dispatch command and receive projected state.
import { h, Component } from "preact";
import { Command, Projection } from "centralpark/preact";

export default Page extends Component {
  render() {
    return (
      <div>
        <Projection
          projector={state => ({ count: state ? state.counter : 0 })}
          render={({ count }) => (
            <div>{count}</div>
          )}
        />
        <Command
          render={dispatchCommand => (
            <button onClick={() => dispatchCommand("increment", {})}>
              Increment
            </button>
          )}
        />
      </div>
    )
  }
}

Credits

Icons made by Icon Pond from www.flaticon.com is licensed by CC 3.0 BY.