useEvaluation for a value, not just a boolean, and a safe default if it fails
Most examples I find use useEvaluation for an on/off flag. I want a component to read an actual value from an evaluation instead, like the visitor's country or a computed tier, and branch on that.
My concern is the failure case. If the query cannot resolve for some reason, I do not want the component to throw and take the UI down. What is the right way to give it a safe default?
2 answers
useEvaluation runs a CQL query and returns its result, and that result can be any value, not only a boolean. So a query like location's country gives you the country back directly:
const country = useEvaluation<string>("location's country", { fallback: 'US',});The fallback is exactly your safety net: if the evaluation cannot resolve, the hook resolves to that default instead of throwing, so the UI keeps rendering. CQL is evaluated in real time per interaction and targets under 20ms, so this is not a slow path, but the fallback covers the case where something does go wrong.
One behaviour to keep in mind while you branch on the value: undefined variables evaluate to false by design. So a condition that reads an attribute the visitor does not have yet resolves to false rather than erroring, which is usually what you want, but it means you should guard the not-yet-known case explicitly rather than assuming a missing value throws.
That covers my case exactly. Value out of the query plus a fallback, and I will handle the undefined branch on purpose. Thanks.