Skip to content

How to toggle a Boolean field in Firebase 9

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.

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

<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(() => {
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);



Uncaught ReferenceError: isFav is not defined

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



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

<span class="material-icons fav_ico" @click="toggleFav(, 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 });
User contributions licensed under: CC BY-SA
3 People found this is helpful