HextaUI

Switch: Saving

Return a promise from onCheckedChange and the switch flips right away, even when it's controlled. A spinner shows in the thumb only if saving takes longer than 400ms. If it rejects, the switch flips back and shakes.

"use client"

import { Switch } from "@/components/ui/switch"

function save(succeed: boolean) {
  return new Promise<void>((resolve, reject) =>
    setTimeout(() => (succeed ? resolve() : reject(new Error("Offline"))), 1200)
  )
}

export function SwitchAsync() {
  return (
    <div className="flex flex-col gap-4 text-sm">
      <label className="flex items-center gap-3">
        <Switch onCheckedChange={() => save(true)} />
        Sync to cloud (saves)
      </label>
      <label className="flex items-center gap-3">
        <Switch defaultChecked onCheckedChange={() => save(false)} />
        Public profile (fails and flips back)
      </label>
    </div>
  )
}

This adds the example as components/examples/switch/async.tsx, together with the Switch component and the HextaUI theme tokens it needs.

pnpm dlx shadcn@latest add https://hextaui.com/r/switch-async.json

To add only the component, follow the Switch installation.

Props in this example

The Switch props this example sets, from the API reference.

PropTypeDefault
defaultChecked
booleanfalse
onCheckedChangeReturn a promise to show the saving state. On rejection an uncontrolled switch flips back.
(checked, details) => void | Promise–

Every prop is in the Switch API reference.

See them all, with keyboard support and accessibility notes, on the Switch page.