Writing state
This is by no means an exhaustive list of state update utilities.
The rest are easily discoverable (and carefully documented) via the fluent API.​
Let's begin with the following store:
import { createStore } from 'olik'
const store = createStore({
name: document.title,
state: {
user: { firstName: '', lastName: '', job: { title: '', contractor: false } },
todos: new Array<{ id: number, name: string, done: boolean, urgency: number }>(),
}
});
Writing object and primitive nodes​
// Replace the selected node with the supplied state.
store.user.age
.$replace(29)
// Add the supplied number onto the selected number.
store.user.age
.$add(1)
// Partially update the selected object node with the supplied state.
store.user
.$patch({ firstName: 'Jeff', lastName: 'Anderson' })
// Recursively merge the supplied object into the selected node.
store.user
.$deepMerge({ age: 21, job: { contractor: true } } )
Writing array nodes​
// Remove all elements from the selected array.
store.todos
.$clear()
// Insert the supplied array element into the selected array.
store.todos
.$insertOne(todo)
// Insert element(s) if they do not already exist or replace them if they do
store.todos
.$repsertMatching.id
.$withOne(todo)
Writing array element nodes​
In order for the library to generate highly descriptive action types, searching for array elements looks a little different from what you might expect.
Note: in the following examples find
is interchangeable with filter
.
// Find an array element by its ID and replace it
store.todos
.$find.id.$eq(3)
.$replace(todo)
// Find an array element by its ID and remove id
store.todos
.$find.id.$eq(3)
.$remove()
// Find an array element buy its ID and replace one of the elements properties
store.todos
.$find.id.$eq(3)
.urgency.$replace(5)
// Apply multiple search clauses with different comparators
store.todos
.$filter.done.$eq(true).$or.urgency.$lt(3)
.$remove()
Performing many writes at once​
Avoid unnecessary render cycles by using the transact()
function.
import { transact } from /* whichever version of olik you've installed */
transact(
() => store.user.$patch({ firstName: 'James', lastName: 'White' }),
() => store.todos.$clear(),
)