reactuals
Version:
A useful package providing a collection of 50+ React hooks and utilities to simplify React development.
48 lines (47 loc) • 1.59 kB
JavaScript
import { useCallback, useState } from "react";
export function useWebBluetooth() {
const [state, setState] = useState({ device: null, error: null });
const isSupported = typeof navigator !== "undefined" &&
"bluetooth" in navigator &&
!!navigator?.bluetooth;
const connect = useCallback(async (options) => {
if (!isSupported) {
setState((prev) => ({
...prev,
error: new Error("Web Bluetooth API not supported"),
}));
return null;
}
// Check if already connected
if (state.device && state.device.gatt?.connected) {
return state.device;
}
try {
const device = await navigator.bluetooth.requestDevice(options);
setState((prev) => ({ ...prev, device, error: null }));
return device;
}
catch (err) {
const error = err instanceof Error
? err
: new Error("Failed to connect to Bluetooth device");
setState((prev) => ({ ...prev, device: null, error }));
return null;
}
}, [isSupported, state.device]);
const disconnect = useCallback(() => {
setState((prev) => {
if (prev.device && prev.device.gatt?.connected) {
prev.device.gatt.disconnect();
}
return { device: null, error: null };
});
}, []);
return {
connect,
disconnect,
device: state.device,
isSupported,
error: state.error,
};
}