Home > Mobile >  How to toggle a Boolean field in Firebase 9
How to toggle a Boolean field in Firebase 9

Time:11-09

I want to toggle a Boolean field value in Firebase 9. I'm using Vue 3

If the value of isFav is true I want to make it false onclick

If the value of isFav is false I want to make it true onclick

It works fine when I set the value of isFav to just false or true. But setting the value as !isFav doesn't work.

<template>
  <!-- books list -->
  <div v-for="book in books" :key="book.id" >
    <span  @click="toggleFav(book.id)">
      favorite
    </span>
    <h2>{{ book.title }} ({{ book.author }})</h2>
    <div>
      <span  @click="completeBook"> done </span>
      <span  @click="EditBook"> edit </span>
      <span  @click="deleteBook(book.id)">
        delete
      </span>
    </div>
  </div>
</template>

<script setup>
import { ref } from "@vue/reactivity";
import { onMounted, onUnmounted } from "@vue/runtime-core";
import { showBooks, books } from "../use/getBooks.js";
import { doc, deleteDoc, setDoc } from "firebase/firestore";
import { db } from "../firebase/config";

onMounted(() => {
  showBooks();
});
function toggleFav(bookid) {
  const data = {
    isFav: !isFav,
  };

  const docRef = doc(db, "books", bookid);
  setDoc(docRef, data, { merge: true });
}
// Delete a Book
function deleteBook(bookid) {
  const docRef = doc(db, "books", bookid);

  deleteDoc(docRef);
}
</script>

Console

Uncaught ReferenceError: isFav is not defined

Maybe I'm not reading the value of isFav first. But how can I do that?

CodePudding user response:

You can pass current value of isFav to toggleFav as shown below:

<span  @click="toggleFav(book.id, book.isFav)">

Then use updateDoc() to update the existing document as shown below:

async function toggleFav(bookid, isFav) {
  const docRef = doc(db, "books", bookid);
  await updateDoc(docRef, { isFav: !isFav });
}
  • Related