'Live updating data in React-native from Firebase(with NestJs)
I'm working learning React Native/Reactjs with NodeJs(NestJs) and Firebase. I have some problems with updating live data. For example, I have and bell icon which represent Notification and I want it to update whenever the data change and show the number of unread noti in database. My code:
API
async getNotifications(data: any): Promise<any> {
const receiverId = data.userId;
const warehouseId = await this.getKhoId(receiverId);
const ref = db.ref('/Notification');
const result = [];
await ref.once('value', function (snapshot) {
if (snapshot.val())
for (let j = 0; j < warehouseId.length; j++)
for (let i = 0; i < snapshot.val().length; i++) {
if (
snapshot.val()[i] &&
snapshot.val()[i].warehouseId == warehouseId[j]
) {
result.push({
content: snapshot.val()[i].content,
read: snapshot.val()[i].read,
time: snapshot.val()[i].time,
number: i,
});
}
}
else return 'None';
});
return result;
}
React Native
useEffect(() => {
const handleData = async () => {
const userId = await SecureStore.getItemAsync("userId");
const numberOfNoti = await axios({
method: "post",
url: "http://192.168.1.8:5000/getNotifications",
data: {
userId: userId,
},
}).then(function (response) {
let val = 0;
if (response.data) {
response.data.forEach((item) => {
if (item.read === 0) {
val++;
}
});
}
return val;
});
setNumberOfNoti(numberOfNoti);
};
handleData();
}, []);
and the component AppBar contain the bell icon:
{numberOfNoti !== 0 ? (
<Badge size={16} style={{ position: "absolute", top: 5, right: 5 }}>
{numberOfNoti}
</Badge>
) : (
void 0
)}
How can I live updating the number in Badge when data in Firebase change? I also have Notification component which contains a list of Notification and updating state of that Notification(from unread to read onPress) and I want to change the Badge number too.
Solution 1:[1]
I realize I can call API to update continuously using setInterval and it looks something like this. I don't know whether it's a proper way or not but it run fine.
useEffect(() => {
const interval = setInterval(() => {
const handleData = async () => {
const userId = await SecureStore.getItemAsync("userId");
const numberOfNoti = await axios({
method: "post",
url: "http://192.168.1.2:5000/getNotifications",
data: {
userId: userId,
},
}).then(function (response) {
let val = 0;
if (response.data) {
response.data.forEach((item) => {
if (item.read === 0) {
val++;
}
});
}
return val;
});
setNumberOfNoti(numberOfNoti);
};
handleData();
}, 1000);
return () => clearInterval(interval);
}, []);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ??t Nguy?n |
