getter-setter-state
v0.0.1
Published
Small JavaScript utility for managing state with accessors and mutators
Downloads
3
Readme
getter-setter-state
Getter-setter-state is a small JavaScript utility for managing state with accessors and mutators. It's not required, but typically you would use this library with a lens library, like ramda
.
Install
npm install getter-setter-state
Usage
const R = require('ramda')
const { Store } = require('getter-setter-state')
const store = Store()
const initial_state = { user: { username: 'bugsbunny' } }
With Ramda Lenses
store.set(R.always(initial_state))
const username_lens = R.lensPath(['user', 'username'])
const username = R.compose(R.defaultTo('No username'), store, R.view(username_lens))
const set_username = R.compose(store.set, R.set(username_lens))
console.log(username()) // logs bugsbunny
set_username('wileecoyote')
console.log(username()) // logs wileecoyote
// Subscribe to changes scoped to a view function
const unsubscribe = store.subscribe(R.view(username_lens), console.log)
set_username('wileecoyote') // no log, because username didn't change
set_username('roadrunner') // logs "roadrunner"
Without Ramda or lenses
store.set(() => initialState)
const get_username = x => x.user.username
const set_username = username => x => ({
...x,
user: {
...x.user,
username
}
})
console.log(store(get_username)) // logs bugsbunny
store.set(set_username('wileecoyote'))
console.log(store(get_username)) // logs wileecoyote
const unsubscribe = store.subscribe(get_username, console.log)
store.set(set_username('wileecoyote')) // no log, because username didn't change
store.set(set_username('roadrunner')) // logs "roadrunner"