# SDUI use case: Build a counter

> Learn how to build a simple custom app using SDUI.

## Overview

This guide walks you through building a basic counter custom app: a heading, a count display, and an "Increment" button that calls your function to update the value.

This custom app will include:

-   A heading ("Counter")
-   Text that displays the current count
-   A button that increments the count by 1

Your function exports one handler: `onRipplingEvent`, and Rippling calls it in two situations:

| Situation | `action` value | What to return |
| --- | --- | --- |
| User opens the page | `init` | The full UI spec |
| User clicks a button | Whatever you named it (e.g. `increment`) | New data to patch into state |

Your handler branches on `action` at the top:

```typescript
import { createSpec } from '@rippling/pebble-sdui-web';
import {
  Button,
  Heading,
  Text,
  VStack,
  render,
  triggerFunction,
} from '@rippling/pebble-sdui-web/catalogs/custom-apps';
import { FunctionContext, FunctionEvent, FunctionResponse } from '@rippling/rippling-sdk';

export async function onRipplingEvent(
  event: FunctionEvent,
  context: FunctionContext,
): Promise<FunctionResponse> {
  const params = (event.parameters ?? {}) as Record<string, string | undefined>;
  const action = params.action;

  if (action === 'init') {
    // Build and return the UI — steps 1–3
  }

  // Handle user interactions — step 4
}
```

* * *

## Build the counter

You will create the following function in the **Tools** > **Developer** > **Functions** app. For more information on creating a function, see [here](https://developer.rippling.com/documentation/rippling-platform/developer/functions/getting-started).

### Step 1: Define your state

Use `createSpec<State>({ state })` to set up the initial values your UI will read and write. The shape you pass in becomes the starting state when the page loads:

```typescript
interface CounterState {
  count: number;
}

const state: CounterState = { count: 0 };
const { $state, $template } = createSpec<CounterState>({ state });
```

> **Note:**
> `$state('/count')` Reads the current value (use in text and logic).

### Step 2: Build the component tree

To keep our layout organized and access Rippling system variables, we wrap our layout logic in a helper function called `renderSpec`. This gives us safe access to the `FunctionContext` so we can get our function's API name.

Use catalog component builders imported from `@rippling/pebble-sdui-web/catalogs/custom-apps` to create UI nodes. Pass properties in `props`, attach event handlers in `on`, and nest child components via `children`:

```typescript
function renderSpec(context: FunctionContext) {
  const state: CounterState = { count: 0 };
  const { $state, $template } = createSpec<CounterState>({ state });
  const functionApiName = context.function.function_api_name; // Safely read from context

  const root = VStack({
    props: { gap: 'space300', align: 'center' },
    children: [
      Heading({ props: { level: 2, text: 'Counter' } }),
      Text({
        props: {
          text: $template`Count is ${$state('/count')}`,
          typestyle: 'typestyleBodyLarge',
        },
      }),
      Button({
        props: { label: 'Increment', appearance: 'PRIMARY' },
        on: {
          press: triggerFunction({
            functionApiName,
            inputs: {
              action: 'increment',
              current: $state('/count'),
            },
            responsePath: '/count',
          }),
        },
      }),
    ],
  });

  return render({ root, state });
}
```

**Why pass `current: $state('/count')` to the button?** Your function is stateless, so it doesn't remember anything between calls. The client browser must send along whatever current values the server needs to do its calculations.

**What's `responsePath`?** When the server function returns a successful result, the client-side renderer writes that exact response directly into this path in state. Setting `responsePath: '/count'` means the returned value overwrites the `count` state, updating the UI automatically.

### Step 3: Render & return the spec

Inside your main `onRipplingEvent` handler, catch the `init` action, invoke your new `renderSpec` helper, and stringify the output into a 200 response body:

```typescript
if (action === 'init') {
  const spec = renderSpec(context);
  return new FunctionResponse({
    body: { spec: JSON.stringify(spec) },
    statusCode: 200,
    headers: {},
    message: '',
  });
}
```

### Step 4: Handle the increment action

When the user presses the button, Rippling calls your function again with `action: 'increment'` and the `current` value in the inputs sent by the button.

Calculate the new counter value directly from the parameter payload:

```typescript
if (action === 'increment') {
  const current = Number(params.current ?? 0);

  return new FunctionResponse({
    // The renderer writes the entire body to responsePath ('/count')
    body: (current + 1) as unknown as Record<string, unknown>,
    statusCode: 200,
    headers: {},
    message: '',
  });
}
```

> **Note:**
> The function doesn't persist state between calls. If data needs to survive a page reload or be shared across users, store it in a [custom object](https://developer.rippling.com/documentation/rippling-platform/data-model/object-types) or your own API and load it on `init`.

The completed function code will look like this:

```typescript
import { createSpec } from '@rippling/pebble-sdui-web';
import {
  Button,
  Heading,
  Text,
  VStack,
  render,
  triggerFunction,
} from '@rippling/pebble-sdui-web/catalogs/custom-apps';
import { FunctionContext, FunctionEvent, FunctionResponse } from '@rippling/rippling-sdk';

interface CounterState {
  count: number;
}

function renderSpec(context: FunctionContext) {
  const state: CounterState = { count: 0 };
  const { $state, $template } = createSpec<CounterState>({ state });
  const functionApiName = context.function.function_api_name;

  const root = VStack({
    props: { gap: 'space300', align: 'center' },
    children: [
      Heading({ props: { level: 2, text: 'Counter' } }),
      Text({
        props: {
          text: $template`Count is ${$state('/count')}`,
          typestyle: 'typestyleBodyLarge',
        },
      }),
      Button({
        props: { label: 'Increment', appearance: 'PRIMARY' },
        on: {
          press: triggerFunction({
            functionApiName,
            inputs: {
              action: 'increment',
              current: $state('/count'),
            },
            responsePath: '/count',
          }),
        },
      }),
    ],
  });

  return render({ root, state });
}

export async function onRipplingEvent(
  event: FunctionEvent,
  context: FunctionContext,
): Promise<FunctionResponse> {
  const params = (event.parameters ?? {}) as Record<string, string | undefined>;
  const action = params.action;

  if (action === 'init') {
    return new FunctionResponse({
      body: { spec: JSON.stringify(renderSpec(context)) },
      statusCode: 200,
      headers: {},
      message: '',
    });
  }

  if (action === 'increment') {
    const current = Number(params.current ?? 0);
    return new FunctionResponse({
      body: (current + 1) as unknown as Record<string, unknown>,
      statusCode: 200,
      headers: {},
      message: '',
    });
  }

  return new FunctionResponse({ body: {}, statusCode: 400, headers: {}, message: 'Unknown action' });
}
```

### Step 5: Add the function to a custom app

1.  In Rippling, open the left sidebar and select **Custom Apps** > **Create app**.
2.  Enter the name of the custom app and select **Create app**.
3.  Select **\+ Add page** > **Function page** > **Continue**.
4.  In the **Search functions** dropdown, select your recently-created app.

![SDUI Counter](https://developer.rippling.com/assets/images/SDUICounter-6d18b83cdab217919f3398d71082041f.png)

Your function will now be rendered within this custom app and can be customized as needed. See [Get started with custom apps](https://developer.rippling.com/documentation/rippling-platform/custom-apps/get-started) for more information on building a custom app.

![SDUI Counter](https://developer.rippling.com/assets/images/SDUICounter-6d18b83cdab217919f3398d71082041f.png)

Source: https://developer.rippling.com/documentation/rippling-platform/sdui/build-a-counter

> For the complete documentation index, see [llms.txt](https://developer.rippling.com/llms.txt). Public pages have a Markdown version at the same URL with .md added.
