Skip to content

scanQrCode

This custom React hook opens the native QR code scanner and returns the scanned content. It tracks the loading state and handles errors.

Code Example

Below is a custom hook that wraps the minipay_scanQrCode RPC call:

typescript
const useScanQrCode = (config: Config) => {
  const [scannedValue, setScannedValue] = useState<string | null>(null);
  const [error, setError] = useState<Error | null>(null);
  const [isPending, setIsPending] = useState(false);
  const { client } = useMiniPayClient(config);

  return {
    scannedValue,
    error,
    isPending,
    async scanQrCode(): Promise<void> {
      if (!client) return;
      setError(null);
      setIsPending(true);
      setScannedValue(null);

      try {
        const result = await client.request({
          method: "minipay_scanQrCode",
          params: [],
        });
        setScannedValue(result);
      } catch (e: unknown) {
        if (e instanceof Error) {
          setError(e);
        }
      } finally {
        setIsPending(false);
      }
    },
  };
};

Simple usage example:

typescript
const { scanQrCode, scannedValue, isPending, error } = useScanQrCode(config);

return (
  <button onClick={() => scanQrCode()}>
    Scan QR Code
  </button>
);