States
Make reactivity with Umbraco States, enabling you to provide a value that multiple others can observe and thereby be updated when the value changes.
Last updated
Was this helpful?
Make reactivity with Umbraco States, enabling you to provide a value that multiple others can observe and thereby be updated when the value changes.
Last updated
Was this helpful?
An Umbraco State is a container for a value, it enables you to create , which is the name of a hook into the States value — An Observable can then be Observed, such observation provides the current value and if the value of the State changes they will all be updated accordingly.
A typical use case is when you need to implement reactivity across class instances. For example, a State is in a Context and the Observer is a Element. For a concrete example, see the article.
The example below demonstrates the basics of working with a State and observing its changes:
This example will result in the following logs:
Umbraco provides built-in State types for common data structures:
Array State
Boolean State
Class State
Number State
Object State
String State
Use the one fitting for your value type.
The Umbraco Element or Controllers come with the ability to observe an Observable.
Observing all changes will result in the callback being executed.
The example below creates a State and then turns the whole state into an Observable, which then can be observed.
The value of a state can be changed via the setValue
method. This replaces the current data with new data.
The following example shows how to change the value of the state to hold item2
and item3
. As the example extends the example from above, it means that item1
is no longer part of the value of this state.
Observe part of a state
With the asObservablePart
method, you can set up an Observable that provides a transformed outcome, based on the State.
In the above example, the asObservablePart
mapping function will be executed every time there is a change to the State. If the result of the method is different than before, it will trigger an update to its observers.
Let's return to the example at the start of this article, to see how an observablePart is triggered in relation to the value of the state.
This example will result in the following logs:
The length
observation only got triggered when the length actually differed.