Skip to main content

Basic React Usage

The first example program shows how to use Causal in the context of a simple React app, built with Next.js. It builds upon the FDL explained the previous sections.

The repo for all Causal code examples is here.

To use Causal you take the following steps:

  • Create a session
  • Run a query
  • Test a feature flag
  • Use the query results
  • Send events

Running the app

If you'd like to run the app, go to the getting-started directory.

$ cd getting-started
$ npm install
$ npm run dev

You can view the running app at http://localhost:3005/react-example?pid=iphone

Code walk through

To view the full source code, please visit react-example.tsx

Generate the causal.ts file

Causal's compiler generates a type safe API from our FDL file. The checked in example already contains the code, but you can regenerate it by invoking the compiler.

## Equivalent to: npx causalc --typescript causal.ts causal.fdl
$ npm run fdlgen

Import the Causal components from the generated causal.ts file

Import the components into pages/react-example.tsx

import { useRouter } from "next/router";
import { useState } from "react";
import {
queryBuilder,
Session,
SessionContext,
useImpression,
} from "../causal";
import { RatingWidget } from "../components/RatingWidget";
import { getOrGenDeviceId, products } from "../utils";

Create a session

Create a session. Creating a session requires a deviceId, which is specific to how you uniquely identify browsers. This example uses the utility function getOrGenDeviceId that creates a random uuid and stores it in a cookie.

export default function Page() {
const router = useRouter();

const session = new Session({ deviceId: getOrGenDeviceId(router) });

const product = products[router.query.pid as keyof typeof products];
if (product == undefined) {
return <></>; // Product not found
}

Set the session context

Set the session context using the standard React context provider pattern. Doing this makes the session available to any child component. You can, of course, also use the session directly.

  return (
<SessionContext.Provider value={session}>
<ProductInfo product={product} />
</SessionContext.Provider>
);
}

Create a query, and use the react hook

In the child component, create a query using the builder pattern. In this case, only one feature is queried, but others can be chained if you are querying more than one.

Use useImpression to request the impression. useImpression utilizes the session that was put into the context earlier. You can also manually pass a session in, if you'd like.

export function ProductInfo({
product,
}: {
product: { name: string; url: string; next: string };
}) {
const [rating, setRating] = useState(0);
const router = useRouter();

const query = queryBuilder().getRatingBox({ product: product.name });
const { impression, flags, error } = useImpression(query);

Process the impression

Check for errors


// check for errors
if (error) {
console.log(
"There is no impression server running yet, but it still works! " +
"Causal is resilient to network and backend outages " +
"because the defaults are compiled in 😃."
);
}

Test the feature flag. In Causal, all features come with a built in on/off feature flag. The feature flag is accessible through the flags object returned by useImpression and session.requestImpression.


return (
<div className="center">
<h1>{product.name}</h1>
<img src={product.url} alt="product image" />

{/* test feature flag */}
{flags?.RatingBox && (
<>

Use the impression data, and wire up events

          {/* use impression data */}
<h3>{impression.RatingBox?.callToAction}</h3>
<RatingWidget
curRating={rating}
onSetRating={(newRating) => {
setRating(newRating);
// wire up events
impression.RatingBox?.signalRating({ stars: newRating });
}}
/>

Congrats

You've finished the basic React walk through. Please continue with the getting started guide so you can see data flowing end to end.

Next up: Seeing the Data

You may also be interested in the following React topics: