Overview
State in a function page is the client-side data model your SDUI spec reads and updates. Components use $state and $bindState to display values, capture input, repeat over arrays, and run local actions without a server round-trip.
For how specs are returned from your function, see Hello World. For component props, see the component catalog.
JSON-pointer state paths
The Pebble SDK uses JSON-pointer syntax for state. Absolute paths start with /:
| State field object structure | Correct path | Incorrect path example |
|---|---|---|
title | /title | title |
form: { title: '' } | /form/title | form.title |
todos: [] | /todos | todos |
Basic state operations
To demonstrate how to manipulate state, here is a standard application state layout that includes a title string, a form object, and toggle states:
interface AppState {
title: string;
showCreateForm: boolean;
form: { title: string };
todos: Array<{ id: string; title: string; done: boolean }>;
}
const state: AppState = {
title: 'Todos',
showCreateForm: false,
form: { title: '' },
todos: []
};
// Destructure helpers from your spec initializer
const { $state, $bindState, repeat } = createSpec<AppState>({ state });
Read state
Use the $state() helper for read-only values. This tells the Rippling UI engine to dynamically listen to that path and re-render the text whenever that specific string changes:
import { createSpec } from '@rippling/pebble-sdui-web';
import { Text } from '@rippling/pebble-sdui-web/catalogs/custom-apps';
interface AppState {
title: string;
form: { title: string };
}
const state: AppState = {
title: 'Todos',
form: { title: '' },
};
const { $state } = createSpec<AppState>({ state });
const heading = Text({
props: { text: $state('/title') },
});
const formTitle = Text({
props: { text: $state('/form/title') },
});
Bind editable values
Use the $bindState() helper for interactive input fields. This establishes a two-way data binding: the component reads the data from state, and any user edits are automatically written right back to that path instantly.
import { createSpec } from '@rippling/pebble-sdui-web';
import { TextInput } from '@rippling/pebble-sdui-web/catalogs/custom-apps';
interface AppState {
form: { title: string };
}
const state: AppState = { form: { title: '' } };
const { $bindState } = createSpec<AppState>({ state });
const titleInput = TextInput({
props: {
label: 'Title',
value: $bindState('/form/title'),
},
});
Client-side state actions
You do not always need to reach out to your server function to modify data. The framework catalog provides client-side action creators like setState, pushState, and removeState to handle common UI interactions instantly.
Update values
Use setState to overwrite a field value in your state (such as toggling visibility flags or resetting modes):
const openCreateForm = Button({
props: { label: 'New todo' },
on: {
// Sets the boolean value at /showCreateForm to true locally
press: setState({ statePath: '/showCreateForm', value: true }),
},
});
Append to arrays
Use pushState to inject items directly into a target array path. You can optionally pass clearStatePath to automatically wipe an input clean after submission:
const addTodo = Button({
props: { label: 'Add' },
on: {
// Appends an object item directly into your /todos state array
press: pushState({
statePath: '/todos',
value: { title: 'New todo', done: false },
clearStatePath: '/form/title', // Resets the text input instantly
}),
},
});
Generate unique items
When users add new items to a list, those items usually need a unique ID so the framework can keep track of them. Use the special string '$id' inside your pushState.value object to handle this automatically.
Before the item gets added to your state, the Pebble engine replaces '$id' with a brand new, random unique ID string.
pushState({
statePath: '/todos',
value: {
id: '$id', // Replaced with a unique string automatically
text: $state('/newTodoText'),
completed: false,
},
clearStatePath: '/newTodoText',
});
The is only valid with pushState.value. This is especially helpful when using repeat('/todos', 'id'), because it ensures every new row gets a stable, unique tracker key.
Remove from arrays
Use removeState to remove an item from an array path:
const deleteTodo = Button({
props: {
label: 'Delete',
appearance: 'TERTIARY',
},
on: {
// Removes the specific item from the target array path using its index or unique key
press: removeState({
statePath: '/todos',
index: todo.$index(), // Targets the current row item's index in a repeat loop
}),
},
});
Templates & computed values
Use createSpec tools to write dynamic calculation rules. When your code runs, the SDK automatically packages these rules so the browser can read them and instantly update what's on the screen whenever your data changes.
Template strings
The $template helper lets you blend regular text with live data paths to build dynamic sentences (e.g., "Hi [Name], you have [Count] items").
When you use data paths inside a text template, you must still use the standard forward-slash (/) folder format to point to your data location.
import { createSpec } from '@rippling/pebble-sdui-web';
import { Text } from '@rippling/pebble-sdui-web/catalogs/custom-apps';
interface AppState {
user: { firstName: string };
unreadCount: number;
}
const state: AppState = {
user: { firstName: 'Alex' },
unreadCount: 3,
};
const { $state, $template } = createSpec<AppState>({ state });
const greeting = Text({
props: {
text: $template`Hi ${$state('/user/firstName')}, you have ${$state('/unreadCount')} unread items.`,
},
});
Conditional values
Use $cond to choose a property value dynamically based on an evaluating condition helper like truthy.
import { createSpec, truthy } from '@rippling/pebble-sdui-web';
import { Text } from '@rippling/pebble-sdui-web/catalogs/custom-apps';
interface AppState {
isAdmin: boolean;
}
const state: AppState = { isAdmin: false };
const { $cond, $state } = createSpec<AppState>({ state });
const adminLabel = Text({
props: {
text: $cond(truthy($state('/isAdmin')), 'Admin', 'User'),
},
});
Visibility conditions
The visible setting controls whether a component actually appears on the user's screen. You can set this to a simple true or false value, or you can use logic checks (like equals) to automatically show or hide an element based on your data (e.g., only showing a delete button if the user's role is set to "admin").
import { createSpec, equals } from '@rippling/pebble-sdui-web';
import { Button } from '@rippling/pebble-sdui-web/catalogs/custom-apps';
interface AppState {
user: { role: string };
}
const state: AppState = { user: { role: 'member' } };
const { $state } = createSpec<AppState>({ state });
const adminButton = Button({
visible: equals($state('/user/role'), 'admin'),
props: { label: 'Admin action', appearance: 'PRIMARY' },
});
Repeat over arrays
When rendering arrays of data, use repeat('/arrayPath', 'key'). This returns two pieces of code you will use to build your list:
- The loop configuration: Tells the layout engine which array to look at.
- The item proxy: A shortcut variable used to target fields inside a single row item.
Paths accessed inside repeated items are relative. They do not use a leading forward slash (/).
// Destructure the loop config (todosRepeat) and the item helper (todo)
const [todosRepeat, todo] = repeat('/todos', 'id');
const todoRows = VStack({
repeat: todosRepeat, // Directs the engine to iterate over the array
children: [
// Uses todo.$('path') for relative read-only access (no leading slash)
Text({ props: { text: todo.$('title') } }),
// Uses todo.$bind('path') for relative two-way binding (no leading slash)
Checkbox({ props: { label: 'Done', value: todo.$bind('done') } }),
],
});
Full code example
Below is a complete, real-world example that puts the above concepts together. It shows how to build a clean Todo app by breaking the UI down into small, easy-to-read builder functions.
It also demonstrates how to dynamically change styles (like adding a line-through to completed items) and how to completely hide a list container when it is empty using neq.
import {
createSpec,
equals,
neq,
type SpecContext,
} from '@rippling/pebble-sdui-web';
import {
Button,
Card,
Checkbox,
Field,
HStack,
PageContent,
Text,
TextInput,
VStack,
pushState,
render,
} from '@rippling/pebble-sdui-web/catalogs/custom-apps';
import {
FunctionContext,
FunctionEvent,
FunctionResponse,
} from '@rippling/rippling-sdk';
type Todo = {
id: string;
text: string;
completed: boolean;
};
type TodoAppState = {
newTodoText: string;
todos: Todo[];
};
type TodoSpec = SpecContext<TodoAppState>;
function createInitialState(): TodoAppState {
return {
newTodoText: '',
todos: [
{
id: 'todo-1',
text: 'Learn about Pebble components',
completed: false,
},
{
id: 'todo-2',
text: 'Build a todo app',
completed: true,
},
],
};
}
function buildAddTodoSection(spec: TodoSpec) {
return VStack({
id: 'addTodoSection',
props: {
gap: 'space300',
},
children: [
Field({
id: 'todoInputField',
props: {
label: 'New Todo',
},
children: [
TextInput({
id: 'todoInput',
props: {
name: 'newTodo',
placeholder: 'Enter a new todo item',
value: spec.$bindState('/newTodoText'),
},
}),
],
}),
Button({
id: 'addButton',
props: {
label: 'Add Todo',
appearance: 'PRIMARY',
isFluid: true,
},
on: {
press: [
pushState({
statePath: '/todos',
value: {
id: '$id',
text: spec.$state('/newTodoText'),
completed: false,
},
clearStatePath: '/newTodoText',
}),
],
},
}),
],
});
}
function buildTodoItems(spec: TodoSpec) {
const [todoRepeat, todo] = spec.repeat('/todos', 'id');
return VStack({
id: 'todoItems',
repeat: todoRepeat,
props: {
gap: 'space200',
},
children: [
HStack({
id: 'todoItem',
props: {
gap: 'space300',
align: 'center',
padding: 'space300',
backgroundColor: 'colorSurfaceContainer',
radius: 'shapeCornerMd',
},
children: [
Checkbox({
id: 'todoCheckbox',
props: {
name: 'completed',
value: todo.$bind('completed'),
},
}),
Text({
id: 'todoText',
props: {
text: todo.$('text'),
decoration: spec.$cond(
equals(todo.$('completed'), true),
'line-through',
'none'
),
color: spec.$cond(
equals(todo.$('completed'), true),
'colorOnSurfaceVariant',
'colorOnSurface'
),
},
}),
],
}),
],
});
}
function buildTodoList(spec: TodoSpec) {
return VStack({
id: 'todoList',
props: {
gap: 'space300',
},
visible: neq(spec.$state('/todos'), []),
children: [
Text({
id: 'todoListTitle',
props: {
text: 'Your Todos',
typestyle: 'typestyleTitleSmall600',
},
}),
buildTodoItems(spec),
],
});
}
function buildTodoCard(spec: TodoSpec) {
return Card({
id: 'todoCard',
props: {
title: 'Todo List',
},
children: [
VStack({
id: 'todoContent',
props: {
gap: 'space400',
padding: 'space400',
},
children: [
buildAddTodoSection(spec),
buildTodoList(spec),
],
}),
],
});
}
function buildTodoPage(spec: TodoSpec) {
return PageContent({
id: 'todoApp',
props: {
size: '776',
alignment: 'CENTER',
},
children: [buildTodoCard(spec)],
});
}
function renderSpec() {
const state = createInitialState();
const spec = createSpec<TodoAppState>({ state });
const root = buildTodoPage(spec);
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()) },
statusCode: 200,
headers: {},
message: '',
});
}
return new FunctionResponse({
body: {},
statusCode: 400,
headers: {},
message: 'Unknown action',
});
}