Skip to content
Advertisement

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.

<template>
  <!-- books list -->
  <div v-for="book in books" :key="book.id" class="book">
    <span class="material-icons fav_ico" @click="toggleFav(book.id)">
      favorite
    </span>
    <h2>{{ book.title }} ({{ book.author }})</h2>
    <div>
      <span class="material-icons done" @click="completeBook"> done </span>
      <span class="material-icons" @click="EditBook"> edit </span>
      <span class="material-icons delete" @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?

Advertisement

Answer

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

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