i have a problem in react native expo push notifications
the main goal of my app is that fetchs data from a google sheet file and display it
in this code the i have fetch method that checks every 20 seconds if new items added update the data
const fetchData = async () => {
setIsFetching(true);
try {
const data = await FetchData();
setValue(data);
const newLength = data.length;
let hasNewItems = false;
if (data && newLength > prevLengthRef.current) {
console.log("New Order Received:",newLength - prevLengthRef.current,"new items added");
await sendNotification(expoPushToken);
hasNewItems = true; // Set flag if new items found
setInitialLength(newLength);
prevLengthRef.current = newLength;
} else {
console.log("No new orders received.");
}
// }
} catch (error) {
console.error("Error:", error.message);
}
in this code it execute the function every 20seconds
fetchData(); // Initial fetch
const intervalId = setInterval(fetchData, 20000); // Fetch data every 20 seconds
return () => clearInterval(intervalId);
}, []);
this is function for sending notification
const sendNotification = async () => {
try {
console.log("Sending push notification...");
// notification message
const message = {
to: expoPushToken,
sound: "default",
title: "New Order ",
body: "Open the app new order received ????",
};
await fetch("https://exp.host/--/api/v2/push/send", {
method: "POST",
headers: {
host: "exp.host",
accept: "application/json",
"accept-encoding": "gzip, deflate",
"content-type": "application/json",
},
body: JSON.stringify(message),
});
console.log("Notification sent successfully!");
} catch (error) {
console.error("Error sending notification:", error);
Alert.alert("Error", "Failed to send notification");
}
};
and it works when i put the function in a Button
<Button title="Send push notification" onPress={sendNotification} />