react-native-sms-consent-api
Version:
A lightweight React Native module for Android's SMS User Consent API. Easily retrieve verification codes from SMS without full SMS permissions.
55 lines (54 loc) • 2.02 kB
JavaScript
import { NativeModules, NativeEventEmitter, Platform, } from "react-native";
import { useEffect, useState } from "react";
const { SmsConsent } = NativeModules;
const SmsConsentTyped = SmsConsent;
export const SmsConsentEmitter = new NativeEventEmitter(SmsConsentTyped);
export const Events = {
SMS_CONSENT_RECEIVED: "EVENT_SMS_CONSENT_RECEIVED",
SMS_CONSENT_ERROR: "EVENT_SMS_CONSENT_ERROR",
};
export function startSmsConsentWatcher() {
if (Platform.OS === "android" && SmsConsentTyped?.startSmsConsentWatcher) {
return SmsConsentTyped.startSmsConsentWatcher();
}
return Promise.resolve();
}
export function stopSmsConsentWatcher() {
if (Platform.OS === "android" && SmsConsentTyped?.stopSmsConsentWatcher) {
return SmsConsentTyped.stopSmsConsentWatcher();
}
return Promise.resolve();
}
export function useSmsConsent(autoStart = true) {
const [retrievedCode, setRetrievedCode] = useState(null);
useEffect(() => {
if (!autoStart || Platform.OS !== "android")
return;
let receivedSub;
let errorSub;
startSmsConsentWatcher()
.then(() => {
receivedSub = SmsConsentEmitter.addListener(Events.SMS_CONSENT_RECEIVED, (event) => {
setRetrievedCode(event.message);
stopSmsConsentWatcher();
receivedSub?.remove();
errorSub?.remove();
});
errorSub = SmsConsentEmitter.addListener(Events.SMS_CONSENT_ERROR, (error) => {
console.warn("[SMS_CONSENT_ERROR]", error);
stopSmsConsentWatcher();
receivedSub?.remove();
errorSub?.remove();
});
})
.catch((err) => {
console.error("Failed to start SMS Consent:", err);
});
return () => {
stopSmsConsentWatcher();
receivedSub?.remove();
errorSub?.remove();
};
}, [autoStart]);
return retrievedCode;
}