Home > Software engineering >  Toggle true/false state on complete button in ReactJs using firebase database
Toggle true/false state on complete button in ReactJs using firebase database

Time:08-20

I am building to do list and I have complete button where I want to toggle true or false state and updating in firebase. I was searching on the platform, there were simillar solutions but not exacly what I needed.

So far I have this 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. I am not sure where is the issue. Any help is appreciate.

CodePudding user response:

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