Search code examples
javascriptreactjsfirebasegoogle-cloud-firestoredesktop-application

Toggle boolean value in Firestore with React App


I'm currently building a TODO app with React and Firestore. It's my first time using firestore, and I have run into an issue.

I have created functions for adding and removing todos from the database and UI. However I ran into some difficulties when trying to toggle the boolean value "completed". This is my current function which is called onClick for the todo items.

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);
  });

It seems I can't toggle the boolean value in this manner as the "!completed" returns undefined.

Any suggestions to how I'm supposed to toggle boolean values with React + Firestore? I tried reading the documentation without success.


Solution

  • You need to first read the document in order to get the value of the completed field and, then, write back the new value.

      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);
          });
      };