UNPKG

react-native-ios-alarmkit

Version:
65 lines (64 loc) 2.27 kB
import { useState, useEffect } from 'react'; import { AlarmKitManager } from './AlarmKitManager'; import { AlarmKitError } from './types'; export function useAlarms() { const [alarms, setAlarms] = useState([]); const [error, setError] = useState(null); const [isLoading, setIsLoading] = useState(true); useEffect(() => { if (!AlarmKitManager.shared.isSupported) { setIsLoading(false); return; } // Subscribe first to avoid race condition where an update // arrives between fetch start and subscription setup const subscription = AlarmKitManager.shared.addAlarmUpdatesListener((updatedAlarms) => { setAlarms(updatedAlarms); setError(null); setIsLoading(false); }); // Then fetch initial state AlarmKitManager.shared .getAlarms() .then((initialAlarms) => { setAlarms(initialAlarms); setIsLoading(false); }) .catch((err) => { setError(AlarmKitError.fromError(err)); setIsLoading(false); }); return () => subscription.remove(); }, []); return { alarms, error, isLoading }; } export function useAuthorizationState() { const [state, setState] = useState('notDetermined'); const [error, setError] = useState(null); const [isLoading, setIsLoading] = useState(true); useEffect(() => { if (!AlarmKitManager.shared.isSupported) { setIsLoading(false); return; } // Subscribe first to avoid race condition const subscription = AlarmKitManager.shared.addAuthorizationUpdatesListener((newState) => { setState(newState); setError(null); setIsLoading(false); }); // Then fetch initial state AlarmKitManager.shared .getAuthorizationState() .then((initialState) => { setState(initialState); setIsLoading(false); }) .catch((err) => { setError(AlarmKitError.fromError(err)); setIsLoading(false); }); return () => subscription.remove(); }, []); return { state, error, isLoading }; }