Defining Stores
To create a store, you can use the store()
function and pass in the initial state:
import { store } from '@davstack/store';
const counterStore = store(0);
Alternatively, you can use store.state()
to define the initial state:
const counterStore = store().state(0);
ℹ️
store(initialState)
and store.state(initialState)
are equivalent and can be used interchangeably.
Defining Actions
Actions are functions that modify the store's state. They can be defined using the actions
method:
const userStore = store()
.state({
name: 'John',
age: 25,
})
.actions((store) => ({
incrementAge() {
store.age.set(store.age.get() + 1);
},
}));
// calling actions
userStore.incrementAge();
Defining Computed Properties
Computed properties are derived values that are automatically updated when the store's state changes. They can be defined using the computed
method:
const userStore = store()
.state({
name: 'John',
age: 25,
})
.computed((store) => ({
fullName: () => `${store.name.use()} Doe`,
}));
// accessing computed properties
const fullName = userStore.fullName.get();
ℹ️
You can still use the computed properties outside of react components by
calling get()
on them. When you use store.computedProperty.get()
, davstack
store will intercept the inner .use()
calls and replace them with .get()
calls.