Creates a store instance.
import {createStore} from 'opstore'
const store = createStore(1)
console.log(store.get()) // 1
Builds a store factory function.
import {createFactory, decr, incr, lpush, lremi, lset, set} from 'opstore'
// Build a custom store factory with just the necessary operators
const createStore = createFactory({decr, incr, lpush, lremi, lset, set})
const store = createStore({list: []})
const listRef = store.ref('list')
listRef.lset(0, 1)
listRef.lset(1, 2)
console.log(listRef.get()) // [1, 2]
Dispatches an operator message.
Gets a state snapshot (the current value).
Notifies observers at any key.
NOTE: A key is a slash-delimited path to a value in the state tree.
Creates a reference to a value in the state tree.
Subscribes to changes to a key’s value in the state tree.
const store = opstore.create(0)
store.subscribe({
next(state) {
console.log(state)
}
})
store.ref().incr() // 1
store.ref().incr() // 2
Adds a middleware function to the middleware stack. This allows for intercepting operations before they are applied.
const store = opstore.create([])
const ref = store.ref()
// Add a simple logger middleware
store.use((op, next) => {
console.log(JSON.stringify(op))
next()
})
ref.lpush(1) // {"type":"lpush","value":1}
Using the ref()
method on the store (see Store methods above) yields a reference instance:
const store = opstore.create({title: 'Hello, world'})
const titleRef = store.ref('title')
// Use the "titleRef" instance to modify the "title" state
The reference instance contains the operator methods. Using references is the only way to change state.
Gets a state snapshot (the current value).
Creates a reference to a value in the state tree, relative to the parent reference.
Subscribe to state changes.
const store = opstore.create({items: []})
const itemsRef = store.ref('items')
itemsRef.subscribe({next: console.log})
itemsRef.lpush(1) // [1]
itemsRef.lpush(2) // [1, 2]
Decrements a numeric value.
const store = opstore.create({count: 0})
const countRef = store.ref('count')
console.log(countRef.get()) // 0
countRef.decr()
console.log(countRef.get()) // -1
Increments a numeric value.
const store = opstore.create({count: 0})
const countRef = store.ref('count')
console.log(countRef.get()) // 0
countRef.incr()
console.log(countRef.get()) // 1
Pushes a value to end of a list.
const store = opstore.create({items: []})
const itemsRef = store.ref('items')
itemsRef.lpush(1)
itemsRef.lpush(2)
console.log(itemsRef.get()) // [1, 2]
Removes a value from a list at the given index.
const store = opstore.create({items: [1, 2]})
const itemsRef = store.ref('items')
itemsRef.lremi(1)
console.log(itemsRef.get()) // [2]
Sets a value in a list at a given index.
const store = opstore.create({items: [1, 2]})
const itemsRef = store.ref('items')
itemsRef.lset(1, 3)
console.log(itemsRef.get()) // [1, 3]
Sets a value at a key.
const store = opstore.create({foo: 1})
const fooRef = store.ref('foo')
fooRef.set(2)
console.log(fooRef.get()) // 2