Triggering actions from a Metabase data app
A Metabase action is a server-defined write operation against the data warehouse — either a basic CRUD operation (insert / update / delete) on a model, or a custom SQL command. Actions are configured ahead of time on the Metabase instance, with their parameters, model bindings, and permissions already set. A data app's job is to invoke an action with the right parameters when the user does something — clicking a button, submitting a form, confirming a destructive prompt.
The mental model
Actions belong to a model. They mutate that model's rows. Concretely:
- Every action has a parent model. In the schema it appears as
schema.models.<modelName>.actions.<actionName>
.
- Model entries are included here only to catalog actions. Do not render models as questions, pass model ids to , or fetch model rows; use semantic-layer queries/questions for read views.
- An action's is either (CRUD on the model) or (custom SQL the user authored).
- Implicit actions have an that says what they do: , , , or variants.
- Each action publishes a list. Each parameter has a (the key the Data App sends), a ( / / / / ), and an optional flag.
- Use to know which fields to render and submit. A create result may include , but that row is only typed as ; use it for lightweight confirmation, then refresh the existing table/question/query data already used by the page. Do not fetch or render the parent model itself.
What's in the schema (and what isn't)
Action entries are only generated when the typed schema includes models. Before writing action-invoking code, make sure the schema was generated with
; with
database=<name-or-id>&include-models=true
, Metabase includes models/actions for that database only. Do not rely on
for actions; question collections only add saved questions.
Before writing any action-invoking code, look at the schema and enumerate what's available under
schema.models.<m>.actions
across the models the app cares about. The schema is your
complete catalog of actions for the instance, not a catalog of model data to display. If a model's
entry has
,
,
, those are the actions invokable. Anything not present doesn't exist as far as the Data App is concerned.
The hook
ts
import { useAction } from "@metabase/embedding-sdk-react/data-app";
const { execute, isExecuting, result, error, reset } = useAction(MyAction);
- Import it from
@metabase/embedding-sdk-react/data-app
. That entry's is the data-app form: it accepts a export or and nothing else. The main entry's is the general SDK hook, which also takes plain objects and raw ids, so it cannot enforce the definition; a data app that imports it from the main entry compiles with an unsynchronized action and fails in production.
- The argument is the export itself, declared in the app's root-level directory (one file per topic, beside , never under ) — pass , not . The hook accepts nothing else in a data app: an inline object, the schema entry, or a spread copy of a definition fails to compile with
Property 'definedWithDefineAction' is missing
. Fix that by adding the export to , not with a cast and not by calling at the hook, which compiles but is never synchronized. A production build then runs the synchronized copy, whose model sits in the app's own collection; the dev preview keeps running the authored action, so an app works before it has ever been synchronized. Do not pass schema.models.<model>.actions.<action>
or its : the entry is a compile error, and the raw id belongs to the original model, which the app's users cannot read, so the call fails on permissions in production.
- Don't write the generics. The definition carries its schema entry, so the hook infers both the parameters object and the discriminated from it: becomes a keyed object ( entries are required keys, each value typed from its ), and / become the kind ( → , → , → , any → , → ). The raw-id form exists only on the SDK's from the main entry, where
useAction<TParameters, TKind>(42)
needs them spelled out since an id describes nothing; a data app never names an action by id.
- — triggers the action. Parameters object is keyed by parameter ; parameters declared are required keys, everything else optional. Returns the response body on success AND throws on failure (the error is also written to state for render-time consumers). Resolves to (without making a request) when is or the SDK is not yet initialized — guard the call site if those cases are reachable.
- No / argument. The hook only ever runs when is called, so a gate option would be redundant. Skip the action by branching in the event handler:
ts
const onClick = async () => {
if (!user.canEdit) return;
await execute({ id: orderId, discount });
};
- — between the call and its resolution. Drive button from this so the user can't double-click into duplicate requests.
- — the response body, discriminated by (or the union when is omitted). before the first call and after . Use it for lightweight confirmation ( after an insert,
result?.["rows-affected"]
after a SQL action), but do not treat create rows as richly typed model rows; refresh surrounding data instead — see After an action runs.
- — the last thrown error, typed
ActionExecuteError | null
. Read fields directly with no cast: , , .
- — clears and back to . Useful after the user acknowledges success or dismisses an error.
The hook does NOT auto-fire on mount. Actions only run when the Data App calls
explicitly.
Canonical usage — a form that creates a row
tsx
import { useAction } from "@metabase/embedding-sdk-react/data-app";
import { CreatePerson } from "../../actions/people.action";
function AddPersonForm({ onCreated }: { onCreated: () => void }) {
const { useState } = React;
const { execute, isExecuting, error, reset } = useAction(CreatePerson);
const [name, setName] = useState("");
const [email, setEmail] = useState("");
async function onSubmit(e: React.FormEvent) {
e.preventDefault();
try {
await execute({ name, email }); // typed: keys match parameter slugs
setName("");
setEmail("");
onCreated(); // ← let the parent refresh dependent data
} catch {
// error is captured into hook state for render-time display
}
}
return (
<form onSubmit={onSubmit}>
<input value={name} onChange={(e) => setName(e.target.value)} />
<input value={email} onChange={(e) => setEmail(e.target.value)} />
<button type="submit" disabled={isExecuting || !name || !email}>
{isExecuting ? "Saving…" : "Add"}
</button>
</form>
);
}
Showing the error message
When
fails, surface both error layers. The hook's
is typed
ActionExecuteError | null
— shape
{ status?, data: { message?, errors? }, isCancelled }
.
is the whole-request failure.
is a per-field validation map keyed by parameter slug (
), or
for whole-request failures. Read both directly, no cast:
tsx
const fieldErrors = error?.data.errors ?? {};
{error ? (
<pre style={{ whiteSpace: "pre-wrap", margin: 0 }}>
{error.data.message ?? "Action failed."}
</pre>
) : null}
{action.parameters.map((parameter) => {
const fieldError = fieldErrors[parameter.slug];
return (
<label key={parameter.slug}>
{parameter.displayName}
<input
aria-invalid={Boolean(fieldError)}
style={{ borderColor: fieldError ? "#dc2626" : undefined }}
/>
{fieldError ? <div role="alert">{fieldError}</div> : null}
</label>
);
})}
Use
(or any element with
) — the messages contain newlines that matter (driver errors include the SQL on its own line). A
collapses them into one wall of text.
Example: submitting a 9-character value into a
column produces
Value too long for column "STATE CHARACTER(2)": "'dadasdasd' (9)";
SQL statement:
UPDATE "PUBLIC"."PEOPLE" SET … WHERE "PUBLIC"."PEOPLE"."ID" = 1 [22001-214]
That whole string is
. Render it as-is.
Don't:
- Render / / instead of — the user loses the only fix-it info they have.
- Render only for validation failures —
error.data.errors[parameter.slug]
is often the actionable "which field and why" detail.
- Paraphrase the message into a "friendlier" version. The raw H2/Postgres/SQL error is more actionable than any rewrite.
After an action runs — keeping the UI honest
When an action succeeds, the data the user sees may be stale. Without an explicit refresh, the list still shows the old rows; the stat tile still shows the old count; the row the user just edited still shows its old values. The action worked, but the UI lies — and there is no warning.
The rule is simple and absolute: after an action resolves successfully, every piece of data on the screen that the action could have changed must be refreshed.
Mapping parameters
Each
entry on a schema action exposes
,
,
, and optionally
. The Data App's job:
-
Object keys in match the parameter strings. Use them as literal string keys — the shape the hook derives from the definition rejects typos at compile time, but only when the argument is the
export (not a bare id).
-
Pick the right input from so the browser provides the correct UX and built-in coercion. The agent never invents the input type from the slug name (a slug called
is still
→
).
| Input element |
|---|
| |
| |
| <input type="checkbox" …>
(or a Mantine /) |
| (or if a time component is expected) |
| — best effort, coerce at the call site |
-
Value types in match . A
parameter wants a
, not a string. With
the input emits a number for
, but
is still a string — coerce at the call site (
) if you're reading the latter.
-
parameters cannot be omitted. Reflected in the TS type: required keys are required.
-
is for labels; never use it as a key.
For implicit actions, the slugs match the model's column names (slugified). For custom SQL actions, slugs are whatever the action's author named the SQL parameters in Metabase. Either way, the schema is the source of truth.
Form-side validation — match the main app
The schema exposes
(and
for type coercion). That's the full validation contract today, matching Metabase's built-in action-execute form.
No length checks, no min/max, no format checks — anything more granular comes back as a BE error after submit (see
Showing the error message).
Schema is the ONLY source of truth. Read
and wire it — nothing else. Don't add
because a field is named
, don't cap a "name" at 100 chars on a hunch, don't set
from the slug. If the schema is silent, the field is unconstrained.
Disable the submit button while the form is invalid. Drive it from the browser's native verdict so
is the only rule in play:
tsx
const [isFormValid, setIsFormValid] = useState(false);
const onFormChange = (e: React.FormEvent<HTMLFormElement>) =>
setIsFormValid(e.currentTarget.checkValidity());
<form onSubmit={...} onChange={onFormChange}>
<input required={parameter.required} />
<button type="submit" disabled={isExecuting || !isFormValid}>Create</button>
</form>
Debugging Checklist
When an action appears to succeed but the screen doesn't update, or a call fails with a 400:
- Log , , and after to confirm the request actually went through and succeeded.
- Confirm was called with the export imported from . Passing the schema entry, an inline object, or a spread copy is a compile error; passing its compiles but leaves untyped and 403s in production, since the authored action is not the one an app's users can run. Calling inside the component compiles too, but scans only , so that action is never copied and also 403s.
- Log the object passed to . Every key must match a parameter from
schema.models.<model>.actions.<action>.parameters
; every value must match its declared .
- List every data view on the screen that reads from the mutated model. Confirm each one's data hook is mounted ABOVE the action trigger so its refresh callback can be passed down.
- Confirm the refresh callback is called AFTER AND that the refresh itself is awaited. When multiple refreshes apply, confirm they're awaited together ().
- For implicit actions, confirm the right matches what you intend ( vs vs ) — picking the wrong action publishes the wrong write.
- If the schema doesn't list an action you expect, the action isn't defined on the instance or the schema file is stale. Regenerate the schema.
Common Mistakes
- Importing from
@metabase/embedding-sdk-react
instead of @metabase/embedding-sdk-react/data-app
. The main entry's hook is the general SDK one and accepts anything, so the definition check never runs.
- Declaring the action anywhere but root-level : inline at the hook, wrapped in inside a component, or under . Only is synchronized.
- Passing
schema.models.<model>.actions.<action>.id
to instead of the export. then accepts any , typos like slip through, and production 403s because the authored action is not the one an app's users can run.
- Forgetting to refresh after a successful action. The UI keeps rendering stale data with no error or warning.
- Rendering / / instead of the real backend message. Always extract / (the diagnostic the user needs is in there) and render it verbatim — see Showing the error message.
- Calling the refresh callback without ing it. The modal dismisses or the form clears before fresh data arrives, leaving the user staring at the stale view for a beat.
- Loading data INSIDE the same component that triggers the action. The hook is below the trigger, so its refresh callback can't be wired up. Lift the data hook to a parent and hand its refresh callback down to the trigger.
- Passing raw strings as parameter values when the slug's is or . Coerce at the call site.
- Letting the trigger fire while a previous request is in flight. Drive from the hook.
- Prepending the action's directly to a local list to skip the refresh. Server-filled defaults (auto-IDs, timestamps, computed columns, derived join columns) diverge from any client-side guess.
- Inventing an action because the user asked for behavior the instance doesn't expose. The schema is the catalog of what exists; surface the gap, don't fake the call.
- Reaching for directly. The sandbox blocks raw network calls to the Metabase origin (raw /XHR work only for external declared in ); the only path to actions is .