Skip to main content

Reading state

Olik supports synchonous reads and the ability to listen for updates to a node​


Let's begin with the following store:
import { createStore } from 'olik'

const store = createStore({
name: document.title,
state: {
todos: new Array<{ id: number, title: string, done: boolean }>(),
showDone: false,
}
});

Reading synchronously​

To read state associated with a node, you can use the $state property.
The following statements are equivalent to each other:

const todos = store.todos.$state;
const todos = store.$state.todos;

Reacting to state changes​

store.todos
.$onChange(todos => /* Update DOM */)

sub.unsubscribe()
// Remember to **always** unsubscribe to avoid a memory leak

Deriving computationally expensive state​

import { derive } from 'olik'

const sub = derive(store.todos, store.showDone)
.$with((todos, showDone) => todos.filter(todo => todo.done === showDone))
.$onChange(todos => /* Update DOM */)

sub.unsubscribe()
// Remember to **always** unsubscribe to avoid a memory leak