I am trying to count in minutes and hours how longer a user is on the app for and display it. I have got the app counting minutes I just cant seem to work out how to track when the app is active or not. Theres documentation on appState but I cannot figure out how to incorporate this into counting. Here is my code:
function Overview() {
const appState = useRef(AppState.currentState);
const [appStateVisible, setAppStateVisible] = useState(appState.current);
const [count, setCount] = useState(0);
const [active, setActive] = useState(false);
useEffect(() => {
const subscription = AppState.addEventListener("change", nextAppState => {
if (appState.current.match(/inactive|background/) && nextAppState === "active") {
setActive(true);
}
appState.current = nextAppState;
setAppStateVisible(appState.current);
console.log("AppState", appState.current);
});
return () => {
subscription.remove();
};
}, []);
useEffect(() => {
const id = setInterval(() => setCount((oldCount) => oldCount + 1), 1000);
return () => {
clearInterval(id);
};
}, []);
return (
<View style={{margin: 32}}>
<View style={{marginBottom: 32}}>
<Text style={{fontSize: 36, fontFamily: 'Roboto_400Regular'}}>Great!</Text>
<Text style={{fontSize: 16, color: '#878787', fontFamily: 'Roboto_400Regular'}}>Average mood 23%</Text>
</View>
<View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
<OverviewContainer title="Weather" value="14 C" />
<OverviewContainer title="Time on app" value={`${(count/60).toFixed(0).toString()} mins`} />
</View>
</View>
);
}
Any help on putting the two together be great, thanks :)
You can access the current appstate as well. How about something like
setCount(if AppState.currentState is active then add one)