Advanced usage
Computed value
A gluon can be computed from other gluons, this is useful when you want to compute a value based on other values.
To do that, you need to use the computed
function:
import { countGluon } from "./gluon";
import { computed } from "stayte";
const doubleGluon = computed(() => countGluon.get() * 2, [countGluon])
const unsubscribe = doubleGluon.subscribe((value) => {
console.log(value) // 20, 40 (and no more)
})
countGluon.set(10) // <-- this will trigger the callback
countGluon.set(20) // <-- this will trigger the callback
unsubscribe()
countGluon.set(30) // <-- this will not trigger the callback
computed
method return a ReadGluon
, so you can use it as usual (subscribe, get, useGluon, etc...) but a ReadGluon
cannot be set, it's mean you cannot update the value of a computed gluon.
Also a ReadGluon
is not persistent, it's mean the callback will be executed everytime the application
or the context is reloaded.
Actually computed
is not able to detect automatically the dependencies
inside the callback, so you need to pass the dependencies as second argument.
Schema validation
Stayte is using zod to validate the default value, the initial value from the source and every new value set by the user of the gluon.
If there is a schema provided in the configuration object, the value will be validated against the schema.
If the value is not valid, the gluon switch to an error mode and the error
property will be filled with the error and the value
will be null
.
import { z } from "zod";
import { gluon } from "stayte";
const countGluon = gluon('count', {
from: 'query',
schema: z.number()
})
countGluon.set('string') // <-- this will trigger the error
console.log(countGluon.error) // ZodError
console.log(countGluon.get()) // null
countGluon.set(10) // <-- this will not trigger the error
console.log(countGluon.error) // null
console.log(countGluon.get()) // 10
error
property will never be filled if there is no schema provided.
Reset a gluon
You can reset a gluon by calling the reset
method:
import { gluon } from "stayte";
const countGluon = gluon('count', {
from: 'query',
defaultValue: 10
})
countGluon.set(20) // <-- this will update the query
console.log(countGluon.get()) // 20
countGluon.reset() // <-- this will reset the value to the default value
console.log(countGluon.get()) // 10