[英]Toggle true/false state on complete button in ReactJs using firebase database
I am building to do list and I have complete button where I want to toggle true or false state and updating in firebase.我正在构建待办事项列表,并且我有完整的按钮,我想在其中切换真或假 state 并在 firebase 中更新。 I was searching on the platform, there were simillar solutions but not exacly what I needed.我在平台上搜索,有类似的解决方案,但不是我需要的。
So far I have this function:到目前为止,我有这个 function:
const completedHandler = (id) => {
const docRef = doc(db, "todos", id);
updateDoc(docRef, {
isCompleted: !initialValues.isCompleted
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error.message);
});
};
The problem is that this is updating the state only once, and it won't change it again, for example if the state is false, it is updating in firebase as true, and that's it.问题是这仅更新 state 一次,并且不会再次更改它,例如,如果 state 为假,它正在 firebase 中更新,并且它是真的。 I am not sure where is the issue.我不确定问题出在哪里。 Any help is appreciate.任何帮助表示赞赏。
Since the value that you write to the database depends on the current value of the field in the database, you'll need to first read the data and then write the new value based on that.由于您写入数据库的值取决于数据库中字段的当前值,因此您需要首先读取数据,然后根据该数据写入新值。 The best way to do this is with a transaction and would look something like:最好的方法是使用事务,看起来像:
import { runTransaction } from "firebase/firestore";
try {
const docRef = doc(db, "todos", id);
await runTransaction(db, async (transaction) => {
const todoDoc = await transaction.get(docRef);
if (!todoDoc.exists()) {
throw "Document does not exist!";
}
const newValue = !todoDoc.data().isCompleted;
transaction.update(docRef, { isCompleted: newValue });
});
console.log("Transaction successfully committed!");
} catch (e) {
console.log("Transaction failed: ", e);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.