Docs
useBluetooth

Connect to Bluetooth devices and manage their state with useBluetooth.

Loading...

Installation

pnpm dlx shadcn@latest add https://usekit.kiron.dev/k/use-bluetooth

Usage

"use client"
 
import { useBluetooth } from "@/hooks/use-bluetooth"
 
export function Component() {
  const { isSupported, isConnected, device, requestDevice, server, error } =
    useBluetooth({
      acceptAllDevices: true,
      optionalServices: ["battery_service"],
    })
 
  if (!isSupported) {
    return <div>Bluetooth is not supported</div>
  }
 
  return (
    <div>
      <button type="button" onClick={requestDevice}>
        Connect to Bluetooth Device
      </button>
      {isConnected && <div>Connected to: {device?.name}</div>}
      {(error as Error) && (
        <>
          <p>Error:</p>
          <pre>{JSON.stringify(error, null, 2)}</pre>
        </>
      )}
    </div>
  )
}

API Reference

Parameters

NameTypeDescriptionDefault ValueOptional
filtersBluetoothLEScanFilter[]Filters to apply when scanning for devices.[]Yes
optionalServicesBluetoothServiceUUID[]Optional services to request when connecting to the device.[]Yes
acceptAllDevicesbooleanIf true, all devices will be accepted.falseYes
navigatorNavigatorThe navigator object to use. If not provided, the default navigator will be used.undefinedYes

Return Values

NameTypeDescription
isSupportedbooleanIndicates if the browser supports Bluetooth.
isConnectedbooleanIndicates if the device is connected.
deviceBluetoothDeviceThe connected Bluetooth device.
requestDevice() => Promise<void>Function to request a Bluetooth device.
serverBluetoothRemoteGATTServerThe GATT server of the connected device.
errorError | nullError object if an error occurred.