Reputation: 497
I am writing a reminder App and I am faced with the challenge of actually detecting date and time changes without the component unmounting and re-mounting.
I want to be able to send a push notification when the date and time is the same as specified by the user.
I have done a couple of google and YouTube searches but it seems no one really has any article or video on this.
Upvotes: 0
Views: 2098
Reputation: 102
You can use luxon
library to get the difference between reminder time and now. Then you call setInterval
with mills value from the diff, thus you synchronize the timer counter with the system clock. See my code below:
import React, { useEffect, useState } from 'react';
import { View } from 'react-native';
import { DateTime } from 'luxon';
const getDateTimeDiffFromNow = (
finishSeconds: number,
): {
minutes: number,
milliseconds: number,
expired?: boolean,
} => {
const now = DateTime.local();
if (now.toSeconds() >= finishSeconds) {
return { minutes: 0, milliseconds: 0, expired: true };
}
const finish = DateTime.fromSeconds(finishSeconds);
return finish
.diff(now, ['minutes', 'milliseconds'])
.toObject();
};
const DateTimer = ({ finishSeconds }: Props) => {
const [diff, setDiff] = useState(() =>
getDateTimeDiffFromNow(finishSeconds),
);
useEffect(() => {
if (diff.expired) {
return;
}
const timeoutId = setTimeout(
() => setDiff(getDateTimeDiffFromNow(finishSeconds)),
diff.milliseconds,
);
return () => clearTimeout(timeoutId);
}, [diff, finishSeconds]);
return (<View />)
};
Upvotes: 0
Reputation: 183
The first solution you can store data in the server and send notification via server. Second solution you can use Headless js in React native to run background process while your app is in the background mode. you can read about headless in below link https://facebook.github.io/react-native/docs/0.60/headless-js-android
Upvotes: 1