import AsyncStorage from '@react-native-async-storage/async-storage'; import { useFocusEffect } from '@react-navigation/native'; import format from 'date-format'; import * as BackgroundFetch from 'expo-background-fetch'; import * as TaskManager from 'expo-task-manager'; import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; import Button from '../components/Button'; import useAppState from '../utilities/useAppState'; const BACKGROUND_FETCH_TASK = 'background-fetch'; const LAST_FETCH_DATE_KEY = 'background-fetch-date'; export default function BackgroundFetchScreen() { const [isRegistered, setIsRegistered] = React.useState(false); const [fetchDate, setFetchDate] = React.useState(null); const [status, setStatus] = React.useState(null); const appState = useAppState(null); React.useEffect(() => { if (appState === 'active') { refreshLastFetchDateAsync(); } }, [appState]); const onFocus = React.useCallback(() => { refreshLastFetchDateAsync(); checkStatusAsync(); }, []); useFocusEffect(onFocus); const refreshLastFetchDateAsync = async () => { const lastFetchDateStr = await AsyncStorage.getItem(LAST_FETCH_DATE_KEY); if (lastFetchDateStr) { setFetchDate(new Date(+lastFetchDateStr)); } }; const checkStatusAsync = async () => { const status = await BackgroundFetch.getStatusAsync(); const isRegistered = await TaskManager.isTaskRegisteredAsync(BACKGROUND_FETCH_TASK); setStatus(status); setIsRegistered(isRegistered); }; const toggle = async () => { if (isRegistered) { await BackgroundFetch.unregisterTaskAsync(BACKGROUND_FETCH_TASK); } else { await BackgroundFetch.registerTaskAsync(BACKGROUND_FETCH_TASK, { minimumInterval: 60, // 1 minute stopOnTerminate: false, startOnBoot: true, }); } setIsRegistered(!isRegistered); }; const renderText = () => { if (!fetchDate) { return There was no BackgroundFetch call yet.; } return ( Last background fetch was invoked at: {format('yyyy-MM-dd hh:mm:ss:SSS', fetchDate)} ); }; return ( Background fetch status:{' '} {status ? BackgroundFetch.Status[status] : null} {renderText()}