State
Set up state with self.get_initial_state
,
read state with state
,
and update state with update
,
:ruby
def self.get_initial_state(initial_count: 0, **) = {
count: initial_count
}
def handle_reset(_event)
update(count: 0)
end
def handle_increment(_event)
update do |count:|
{ count: count + 1 }
end
end
def handle_decrement(_event)
update do |count:|
{ count: count - 1 }
end
end
%div
%p Count: #{state[:count]}
%button(onclick=handle_decrement) Decrement
%button(onclick=handle_reset) Reset
%button(onclick=handle_increment) Increment
:css
p { margin-top: 0; }
button { margin-right: .5em; }
This will result in the following component:
Count: 0
Different ways to update
If you don’t need to read state when updating, you can do this:
update(count: 0)
If you need to read state, you can get the entire state object:
update do |state|
{ count: state[:count] + 1 }
end
Or you could extract just the keys you are interested in:
update do |count:|
{ count: count + 1 }
end
You can also use default values:
update do |count: 0|
{ count: count + 1 }
end