【发布时间】:2023-03-15 03:46:01
【问题描述】:
我当前的设置是在页面加载时提取 firebase 数据,这很棒,但现在我需要我的应用程序上的数据实时更新我该怎么做?
useEffect(() => {
const user = Authentication.auth().currentUser;
{
user !== null &&
Authentication.firestore().collection('Health_data')
.doc(user.uid)
.get()
.then(doc => {
healthDataSet(doc.data())
setLoading(false)
}).catch(function (error) {
console.error("Error reading health", error);
});
}
return () => {
document.body.style.overflow = 'unset';
}
}, []);
//calculates calorie requirments
useEffect(() => {
if (!loading && healthData !== null) {
if (healthData.units === 'Kg') {
BMIset(Math.round((healthData.weight / ((healthData.height / 100) * (healthData.height / 100))) * 10) / 10)
if (healthData.gender === 'female') {
BMRset(Math.round(((655.1 + (9.563 * healthData.weight) + (1.850 * healthData.height) - (4.676 * healthData.age)) * 1.37) * 0.8))
} else {
BMRset(Math.round(((88.2 + (13.362 * healthData.weight) + (4.799 * healthData.height) - (5.677 * healthData.age)) * 1.37) * 0.8))
}
}
if (healthData.goal === 'Gain') {
if (healthData.gender === 'female') {
BMRset(Math.round(((655.1 + (9.563 * healthData.weight) + (1.850 * healthData.height) - (4.676 * healthData.age)) * 1.37) * 1.2))
} else {
BMRset(Math.round(((88.2 + (13.362 * healthData.weight) + (4.799 * healthData.height) - (5.677 * healthData.age)) * 1.37) * 1.2))
}
}
if (healthData.goal === 'Recomp') {
if (healthData.gender === 'female') {
BMRset(Math.round((655.1 + (9.563 * healthData.weight) + (1.850 * healthData.height) - (4.676 * healthData.age)) * 1.37))
} else {
BMRset(Math.round((88.2 + (13.362 * healthData.weight) + (4.799 * healthData.height) - (5.677 * healthData.age)) * 1.37))
}
所以这是我在提取数据后的代码,数据用于计算我想要它,所以当数据像这样更新时。
const updateWeight = () => {
if (Weight !== null) {
database.collection('Health_data').doc(localStorage.getItem('user')).update({
weight: Weight
}).catch((error) => {
alert(error.message)
console.log('failed to write', error);
});
} else {
alert('A weight must be in put')
}
}
计算得到新信息,页面实时更新可以吗?
【问题讨论】:
-
我建议从文档开始了解它是如何工作的:firebase.google.com/docs/firestore/query-data/listen
-
这是我一直在寻找的网站,谢谢队友,但实施起来没有运气
-
在 Stack Overflow 上,建议您发布未按预期方式运行的代码,并说明问题所在。
标签: javascript json reactjs firebase google-cloud-firestore