Query evaluation
Learn how to evaluate queries in real-time.
This guide provides practical examples of using the React SDK to evaluate CQL queries from your application.
Basic usage
To evaluate queries in real-time, you can use either the useEvaluation hook or the <Personalization> component, depending on whether you prefer an imperative or declarative approach.
Here is an example:
import {useEvaluation} from '@croct/plug-react';export function DocsLink() {const isDeveloper = useEvaluation("user's persona is 'developer'");return (isDeveloper? <a href="/docs">View docs</a>: <a href="/share">Share with your developer</a>);}
If you are using a server-side rendering framework, you should also provide an initial value for pre-rendering, which will then be personalized on the client.
Note that the result of the evaluation is not limited to boolean values. For example, you can use the following query to find out the location from which the user is accessing your application:
import {useEvaluation} from '@croct/plug-react';export function Location() {const location = useEvaluation("location");return (<address>{location.city}, {location.state} - {location.country}</address>);}
In this case, the result of the evaluation is a geographic location, and the output would look like this:
<address>San Francisco, California - United States</address>
By the way, the example above is personalized using the <Personalization> component directly in MDX.
Fault tolerance
You should always provide a fallback value when evaluating queries to make your application resilient to unexpected errors, downtime, and network failures.
All you have to do is specify the result you want to use as a fallback:
import {useEvaluation} from '@croct/plug-react';export function Greeting() {const returning = useEvaluation("user is returning", {fallback: false,});return returning ? <p>Welcome back!</p> : <p>Welcome!</p>;}
In this example, the result is set to false if the evaluation fails, ensuring that the application will work even if the evaluation fails.
Context variables
In some cases, you may want to pass additional information that can be used by the query in the evaluation process.
For example, let's say you want to check whether the user is accessing your application from one of a list of countries. The SDK allows you to pass this information as an attribute to the query:
import {useEvaluation} from '@croct/plug-react';export function ConditionalFeature() {const enabled = useEvaluation("context's countries include location's country", {attributes: {countries: ['United States', 'Canada', 'Mexico']},});return enabled ? 'Available' : 'Unavailable';}
Any attribute passed in the attributes option will be available in the query as a context variable.