In this section we'll walk through a simple counter example and learn how to update the state via actions.
app({
state: 0,
view: (state, actions) => (
<main>
<h1>{state}</h1>
<button onclick={actions.add}>+</button>
<button onclick={actions.sub} disabled={state <= 0}>-</button>
</main>
),
actions: {
add: state => state + 1,
sub: state => state - 1
}
})
The entire state is a number and its initial value is 0.
state: 0
When the app function runs for the first time, the state is passed to the view and its value is displayed inside an <h1> tag.
<h1>{state}</h1>
There are also two buttons in the view that have onclick handlers attached to them. The handlers are the actions that get passed to the view as the second argument.
<button onclick={actions.add}>+</button>
<button onclick={actions.sub} disabled={state <= 0}>-</button>
The disabled attribute is dynamically toggled depending on the value of the counter. This prevents the decrement button from being clicked when the counter reaches zero.
disabled={state <= 0}
Notice that neither actions.add or actions.sub update the state directly, instead, they return a new state.
add: state => state + 1,
sub: state => state - 1
When the state is updated as a result of calling an action, the view function is called and the application is rendered again.