Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 10 additions & 7 deletions dist/index.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,31 @@
import { useState, useEffect } from 'react';
import { AppState } from 'react-native';
import { useState, useEffect } from "react";
import { AppState } from "react-native";

export default function useAppState(settings) {
const { onChange, onForeground, onBackground } = settings || {};
const [appState, setAppState] = useState(AppState.currentState);

useEffect(() => {
function handleAppStateChange(nextAppState) {
if (nextAppState === 'active' && appState !== 'active') {
if (nextAppState === "active" && appState !== "active") {
isValidFunction(onForeground) && onForeground();
} else if (appState === 'active' && nextAppState.match(/inactive|background/)) {
} else if (
appState === "active" &&
nextAppState.match(/inactive|background/)
) {
isValidFunction(onBackground) && onBackground();
}
setAppState(nextAppState);
isValidFunction(onChange) && onChange(nextAppState);
}
const appState = AppState.addEventListener('change', handleAppStateChange);
const appState = AppState.addEventListener("change", handleAppStateChange);

return () => appState.remove();
return () => appState?.remove();
}, [onChange, onForeground, onBackground, appState]);

// settings validation
function isValidFunction(func) {
return func && typeof func === 'function';
return func && typeof func === "function";
}
return { appState };
}