Skip to content
Optima docs
SDKsReact Native SDK

Forms

React Native SDK v1.2.0 — Forms

This SDK ships both headless form loading and submission (forms.load/the bound submit) and a minimal native renderer (<OptimaForm>), plus a link into the hosted, server-rendered form page for cases where neither is worth building against.

<OptimaForm>

The fastest path for a simple form:

import { OptimaForm } from "@optima/react-native/ui";

<OptimaForm
  id="newsletter-signup"
  submitLabel="Subscribe"
  onSuccess={({ doubleOptIn }) => console.log("submitted", { doubleOptIn })}
  onError={(e) => console.warn("form error", e.kind, e.message)}
/>;

It loads the definition on mount (via forms.load(id, {lang, assertion})), renders each field with a plain TextInput (keyboard type inferred from inputType: email-address/phone-pad/numeric/default), a Switch for checkbox fields, or a pressable option row for select fields only — any other inputType (including a hypothetical radio) falls back to the plain TextInput branch, since there is no dedicated radio-group renderer in this release; validates required fields client-side before allowing submit (showing a "Required: ..." message naming the missing labels rather than submitting); disables the submit button while a submission is in flight (and guards against a double-tap firing two submits); and shows definition.successMessage (plus a double-opt-in confirmation hint when applicable) on an accepted outcome, or an inline error message otherwise. FormErrorInfo ({kind: "not_found" | "failed" | "rejected" | "validation"; message?}) is what onError receives — "not_found"/"failed" come from a failed load, "rejected"/"validation" from a failed submit.

<OptimaForm> resets and reloads whenever id, lang, or assertion changes — all local state (loaded definition, field values, messages, success) is cleared and forms.load is called again. It also guards against setting state after unmount (a submission that resolves after the component has unmounted is a no-op, not a warning-triggering setState). There is no prop to customize individual field rendering — for a form that needs a particular look, use the headless API below and build your own screen.

Headless: loading and submitting a form

const result = await Optima.instance.forms.load("newsletter-signup");

forms.load(id, opts) returns a discriminated-union FormResult:

  • {kind: "loaded", definition, submit} — the happy path. definition: FormDefinition carries fields: FormField[] (each with key, kind, inputType, label, placeholder, required, options for select/radio-style fields), plus successMessage, successRedirectUrl, doubleOptIn, and minSubmitIntervalSec. submit is a bound closure — (values: Record<string, unknown>) => Promise<SubmitResult> — that already carries the form's render nonce internally; you never see or handle the nonce yourself.
  • {kind: "not_found"} — the form id doesn't exist or isn't published.
  • {kind: "failed", status?, cause?} — a network failure or an unexpected status.

A minimal custom form built from a loaded definition:

function NewsletterForm({ formId = "newsletter-signup" }) {
  const [result, setResult] = useState<FormResult | null>(null);
  const [values, setValues] = useState<Record<string, string>>({});
  const [outcome, setOutcome] = useState<SubmitResult | null>(null);

  useEffect(() => { void Optima.instance.forms.load(formId).then(setResult); }, [formId]);

  if (!result) return <ActivityIndicator />;
  if (result.kind === "not_found") return <Text>This form is no longer available.</Text>;
  if (result.kind === "failed") return <Text>Couldn't load the form — check your connection.</Text>;

  return (
    <View style={{ padding: 16 }}>
      {result.definition.fields.map((field) => (
        <TextInput
          key={field.key}
          value={values[field.key] ?? ""}
          onChangeText={(v) => setValues((m) => ({ ...m, [field.key]: v }))}
          placeholder={field.label + (field.required ? " *" : "")}
        />
      ))}
      <Button title="Submit" onPress={() => void result.submit(values).then(setOutcome)} />
      {outcome?.kind === "accepted" && <Text style={{ color: "green" }}>{result.definition.successMessage ?? "Thanks!"}</Text>}
      {outcome?.kind === "rejected" && <Text style={{ color: "red" }}>Please check your entries.</Text>}
      {outcome?.kind === "failed" && <Text style={{ color: "red" }}>Something went wrong — try again.</Text>}
    </View>
  );
}

submit's value map accepts string, boolean, and finite number; anything else for a given key is silently dropped (a debug log names the field) rather than failing the whole submission — so a stray null or an unexpected object type in your values map costs you that one field, not the user's submission.

The honeypot and the nonce, handled for you

Every submission includes an empty honeypot field (_hp) and the render nonce the form definition carried privately — both anti-bot measures the hosted form page also uses, and both are wired up inside submit(...) without any action on your part. You cannot see or tamper with either from the public API, by design: there is nothing to configure and nothing that can be gotten wrong here.

409 means "already submitted"

If the device has already submitted this form (the server enforces min_submit_interval_sec and/or a one-submission-per-device rule server-side), the submit endpoint answers 409, and the SDK treats that as a success, not an error: {kind: "accepted", dropped: [], doubleOptIn: definition.doubleOptIn}, and a form:submitted event fires the same as a genuine first-time acceptance. Don't special-case 409 in your own UI — by the time it reaches SubmitResult, it's already been normalized into the same "it worked" shape as a real 200.

Double opt-in

When definition.doubleOptIn is true (or the server's response to a submission says so — the accepted result's doubleOptIn reflects whatever the server actually decided, which can differ from the definition's declared default in edge cases), the profile's consent for whatever the form grants is not yet active — a confirmation email/link has to be completed first. There's nothing further for the SDK to do here: the confirmation flow runs entirely server-side (GET/POST /edge/v1/forms/confirm/:token, addressed by a link in an email, deliberately outside any mobile deep link — a GET must never mutate, so a mail-scanner can't manufacture consent). Surface doubleOptIn = true in your own UI as "check your email to confirm" copy — <OptimaForm> does this for you automatically.

Hosted pages

For a form you don't want to build (or maintain) a native screen for — a long multi-section form, or one that changes frequently and you'd rather not ship an app update for — open the operator's hosted, server-rendered page instead:

import { Linking } from "react-native";

const url = Optima.instance.forms.pageUrl("https://edge.shop.example/edge/v1/pages/<sdk-key-token>/newsletter-signup");
void Linking.openURL(url);

Prefer expo-web-browser (WebBrowser.openBrowserAsync(url)) or a Custom-Tabs-style in-app browser library if you want the page to open inside your app's chrome rather than handing off to the system browser — the SDK has no opinion on which; forms.pageUrl only builds the URL.

forms.pageUrl(url) appends device_id=<id> as a query parameter (creating the ? if the URL doesn't already have one) — this is what lets the hosted page's own submission attribute back to the same device identity the rest of the SDK uses, so a form filled out in the browser and an identify(...) call made natively both resolve to the same profile. The hosted page URL itself (/edge/v1/pages/:token/:slug) is addressed by SDK-key token rather than by X-Edge-Key header, because a browser navigation can't send a custom header; get the exact URL for a given form from the Optima console's forms admin screen.

assertion

Both <OptimaForm> and headless forms.load accept an assertion (IdentityAssertion) — the same signed identity assertion identify() accepts (see chapter 3). Pass one when you already know who the visitor is (e.g. inside an authenticated in-app flow) and want the form's submission to attach to that specific customer rather than create/attach an anonymous claim; minted by your backend with the SDK key's identify secret, never something the app itself constructs.

On this page