Careful, there are a few things in your post that make me think you have the wrong mental model.
first, the update()
method. This works by returning a new value based on the previous one. However, you try to modify the parameter:
// BAD
#state("test", 0).update(cs => {
// this statement has no result, only a side effect
// its result is thus implicitly none
cs += 1
// the block ends here, returning the last expression's value
// instead of incrementing, the state is now none
})
// GOOD
#state("test", 0).update(cs => {
cs + 1
// the block ends here, returning 1
})
second, you’re not actually retrieving the state’s current value:
// BAD: you're just looking up the metadata
#context query(<test>)
// gives (metadata(value: state("test", 0)),)
// BETTER: extracting the state out of the metadata
#context query(<test>).first().value
// gives state("test", 0)
// GOOD
#context query(<test>).first().value.get()
// gives the actual state value
the state itself is not modified by an update, thus the “BETTER” code always has a 0 inside: that’s how the state was set up. Only with get()
do you extract the value.
Finally, both states and labels have globally unique names, so putting state inside labelled metadata doesn’t bring much benefit. Also, state is only identified by the name:
#metadata(state("test", 0)) <test>
#metadata(state("test", 0)) <test2>
#context query(<test>).first().value.update(cs => cs + 1)
#context query(<test2>).first().value.get()
// prints 1, because the "test" state was updated
Thus, I’d recommend to just replace labels with state names, that makes more sense.
One final note on something peculiar – consider this:
#metadata(state("test", 0)) <test>
#metadata(state("test", 1)) <test2>
#context query(<test>).first().value.update(cs => cs + 1)
#context query(<test2>).first().value.get()
// prints 2, because the "test" state was updated from its initial value of 1
state updates affect all state “objects” of the same name, but the initial value of the specific object matters! It’s therefore not recommended to create multiple different states. My recommendation is to put each state in a variable and import that variable.