使用 React App 在 Firestore 中切换布尔值

Toggle boolean value in Firestore with React App

我目前正在使用 React 和 Firestore 构建一个 TODO 应用程序。 这是我第一次使用 firestore,我 运行 遇到了问题。

我已经创建了用于在数据库中添加和删除待办事项的函数 UI。 但是,我 运行 在尝试切换布尔值“完成”时遇到了一些困难。 这是我当前的函数,它为待办事项调用 onClick。

const todos = firebase.firestore().collection("todos");

markComplete = (id) => {
  todos
   .doc(id)
   .update({ completed: !completed })
   .then(function () {
     console.log("Todo successfully updated!");
  })
  .catch(function (error) {
    // The document probably doesn't exist.
    console.error("Error updating todo: ", error);
  });

似乎我无法以这种方式切换布尔值,因为“!已完成”returns 未定义。

关于我应该如何使用 React + Firestore 切换布尔值的任何建议? 我尝试阅读文档但没有成功。

您需要先读取文档以获取completed字段的值,然后写入 返回新值。

  markComplete = (id) => {
    todos
      .doc(id)
      .get()
      .then(function (doc) {
        if (doc.exists) {
          return doc.ref.update({ completed: !doc.data().completed });
        } else {
          // Throw an error
        }
      })
      .then(function () {
        console.log('Todo successfully updated!');
      })
      .catch(function (error) {
        // The document probably doesn't exist.
        console.error('Error updating todo: ', error);
      });
  };