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.
JavaScript
x
43
43
1
<template>
2
<!-- books list -->
3
<div v-for="book in books" :key="book.id" class="book">
4
<span class="material-icons fav_ico" @click="toggleFav(book.id)">
5
favorite
6
</span>
7
<h2>{{ book.title }} ({{ book.author }})</h2>
8
<div>
9
<span class="material-icons done" @click="completeBook"> done </span>
10
<span class="material-icons" @click="EditBook"> edit </span>
11
<span class="material-icons delete" @click="deleteBook(book.id)">
12
delete
13
</span>
14
</div>
15
</div>
16
</template>
17
18
<script setup>
19
import { ref } from "@vue/reactivity";
20
import { onMounted, onUnmounted } from "@vue/runtime-core";
21
import { showBooks, books } from "../use/getBooks.js";
22
import { doc, deleteDoc, setDoc } from "firebase/firestore";
23
import { db } from "../firebase/config";
24
25
onMounted(() => {
26
showBooks();
27
});
28
function toggleFav(bookid) {
29
const data = {
30
isFav: !isFav,
31
};
32
33
const docRef = doc(db, "books", bookid);
34
setDoc(docRef, data, { merge: true });
35
}
36
// Delete a Book
37
function deleteBook(bookid) {
38
const docRef = doc(db, "books", bookid);
39
40
deleteDoc(docRef);
41
}
42
</script>
43
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:
JavaScript
1
2
1
<span class="material-icons fav_ico" @click="toggleFav(book.id, book.isFav)">
2
Then use updateDoc()
to update the existing document as shown below:
JavaScript
1
5
1
async function toggleFav(bookid, isFav) {
2
const docRef = doc(db, "books", bookid);
3
await updateDoc(docRef, { isFav: !isFav });
4
}
5