live.set()
live.set() is a somewhat low-level way to set the underlying value of a live variable.
To set a property on a live variable (such as a key on the component state variable $
), traditional property setting like $.key = value is a simpler way of setting live variables. live.set()'s primary use case is when only a reference to the live variable itself is available (such as in low-level utility functions).
Note: To delete a live variable, that is, remove it from its parent object, use live.delete()
.
Syntax
live.set($live, value);
Parameters
- $live
- A live variable to set. The value technically does not need to be live, nor settable, but in those cases live.set() does nothing.
- value
- The new value for the live variable. If this is a live variable itself, then it is unwrapped first.
Return value
A boolean indicating whether the value was successfully set or not (true if it was successful, false otherwise).
If the $live argument is not live, then the value is not set and false is returned. If the live variable is not settable, for example when passing $object.$foo when $object is wrapping null, then also live.set() fails and false is returned. Otherwise, setting should be successful and true is returned.
Details
Setting a live variable (either through live.set() or setting a property the traditional way) does not add it to the monitored context of type "live". However, if the value argument is a live variable, it is unwrapped before the setting happens, which means the value variable is then added to the monitored context.
Examples
Manual state
When creating a live variable manually (through live()
) to keep track of state, it is possible, though not advised, to use a single live variable for a single primitive value. In this example, we'll create a $number variable that represents a number, and then we'll create a $double variable linked to it using live.link()
.
const $number = live(23);
const $double = live();
live.link($double, () => live.get($number) * 2);
console.log(live.get($double)); // 46
live.set($number, 5);
console.log(live.get($double)); // 10
However, the recommended way to keep track of state is to create a live container object. This allows for regular property setting and accessing, making for clearer, simpler code.
const $state = live({ number: 23 });
live.link($state.$double, () => $state.number * 2);
console.log($state.double); // 46
$state.number = 5;
console.log($state.double); // 10
Note that it completely removes the need for live.get() and live.set() calls. Additionally,
See also