1.0.4 • Published 5 years ago

riot-state v1.0.4

Weekly downloads
8
License
MIT
Repository
github
Last release
5 years ago

riot-state

Simplest centralized state management for Riot.JS

⚙ CodeSandbox Example

Usage

A riot-state store consists of following properties: name, state, actions. And provides following methods: dispatch, install

Store name

Property name is required if initial state would load from a global object. By default riot-state loads initial data from document.__GLOBAL_SHARED_STATE [name]

If there are more than one store it is possible to access them in an action context by name.

const actions = {
  ping(){
    this.Stores.storeName.dispatch('pong')
  }
}
State

A flat javascript object.

Actions

A javascript object containing functions. An action cannot be an arrow function

Component context

A component has to provide a list of shared variables that will be injected in component scope.

export default {
  shared: ['foo', 'bar']
}

Example:

//store.js
import { createStore } from "./state";

const name = "example";

const state = {
  number: 0
};

const actions = {
  increment(value = 1) {
    this.number += value;
  },

  decrement(value = 1) {
    this.number -= value;
  }
};

export default createStore({
  name,
  state,
  actions
});
<number>
  <div class="number">
    {number}
  </div>
  <script>
    import store from './store'
    export default ()=> ({
      shared: [
        'number'
      ],
      onMounted(){
        store.install(this)
        this.update()
      },
      onUpdated(){
        console.log(this.number)
      }
    })
  </script>
</number>
<controls>
  <button onclick={plus}>+</button>
  <button onclick={minus}>-</button>
  <script>
    import store from './store'
    export default () => ({
      onMounted(){
        store.install(this)
      },
      plus(){
        store.dispatch('increment')
      },
      minus(){
        store.dispatch('decrement')
      },
    })
  </script>
</controls>

License

MIT

1.0.4

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago