0.1.24 • Published 4 years ago

js-stores v0.1.24

Weekly downloads
1
License
LGPL-3.0
Repository
github
Last release
4 years ago

js-stores

A small store library (using "Immer" internally)

Licence npm version Build status Coverage status

Installation

npm install --save js-stores

Usage

import { defineMessages } from 'js-messages'
import { createStore, HandlerFactory } from 'js-stores'

const CounterActions = defineMessages({
  increment: (delta: number = 1) => ({ delta }),
  decrement: (delta: number = 1) => ({ delta }),
  reset: {}
})

type CounterState = { count: number }

type CounterHandlerFactory =
  HandlerFactory<CounterState, typeof CounterActions>

const createCounterHandler: CounterHandlerFactory = () => {
  return {
    increment(model, { delta }) {
      model.count += delta
    },

    decrement(model, { delta }) {
      model.count -= delta
    },

    reset(model) {
      model.count = 0
    }
  }
}

const store = createStore(createCounterHandler, { count: 0 })

console.log('Initial state:', store.getState())

const unsubscribe = store.subscribe(() => {
  console.log('New state:', store.getState())
})

store.dispatch(CounterActions.increment())
store.dispatch(CounterActions.increment())
store.dispatch(CounterActions.increment())
store.dispatch(CounterActions.increment(10))
store.dispatch(CounterActions.reset())
store.dispatch(CounterActions.decrement(3))

unsubscribe()

store.dispatch(CounterActions.decrement(4))
console.log('Final state:', store.getState())

/*
  Output:
  
  Initial state: { count: 0 }
  New state: { count: 1 }
  New state: { count: 2 }
  New state: { count: 3 }
  New state: { count: 13 }
  New state: { count: 0 }
  New state: { count: -3 }
  Final state: { count: -7 }  
*/

License

"js-stores" is licensed under LGPLv3.

Project status

"js-stores" is currently in alpha status.

0.1.24

4 years ago

0.1.23

4 years ago

0.1.22

4 years ago

0.1.21

4 years ago

0.1.20

5 years ago

0.1.19

5 years ago

0.1.18

5 years ago

0.1.14

5 years ago

0.1.13

5 years ago

0.1.12

5 years ago

0.1.11

5 years ago

0.1.10

5 years ago

0.1.9

5 years ago

0.1.8

5 years ago

0.1.7

5 years ago

0.1.6

5 years ago

0.1.5

5 years ago

0.1.4

5 years ago

0.1.3

5 years ago

0.0.13

5 years ago

0.0.11

5 years ago

0.0.10

5 years ago

0.0.9

5 years ago

0.0.8

5 years ago

0.1.1

6 years ago

0.1.0

7 years ago