I am facing an issue where I need to compare a string obtained from Firebase in document.check1 with specific strings (hardcoded in the function below) and display content accordingly. Currently, I know how to trigger this comparison on button click, but I want it to happen automatically as soon as the page loads, without requiring user interaction. However, when I attempt to do so, I encounter an error indicating that the value is null. How can I make it wait for the data to be fetched automatically?
<template>
<router-link to="/konto">Back</router-link>
<div v-if="document">
<div>
<span>1:</span>
{{ document.check1 }},
<span>2:</span>
{{ document.check2 }},
<span>3:</span>
{{ document.check3.length }}
</div>
</div>
<button v-if="itWorkOk" @click="documentCheck">Show Content after finding result</button>
<div v-if="isOther">
<p>Content</p>
</div>
</template>
<script>
import getUser from "../composables/getUser";
import getDocument from "../composables/getDocument";
import { ref } from "@vue/reactivity";
export default {
props: ["id", "document"],
setup(props) {
const { error, document } = getDocument("AllData", props.id);
const { user } = getUser();
const itWorkOk = ref(true);
const result1 = ref("");
const isOther = ref("");
const documentCheck = async () => {
const isItOk = document.value.check1
if (isItOk == "Result One") {
result1.value = true;
itWorkOk.value = false;
} else {
isOther.value = true;
itWorkOk.value = false;
}
};
return {
error, user, document, documentCheck, result1, isOther, itWorkOk,
};
},
};
</script>
The error (when I put function to call immediately):
Uncaught (in promise) TypeError: document.value is null
The getDocument code:
import { ref, watchEffect } from 'vue'
import { projectFirestore } from '../firebase/config'
const getDocument = (collection, id) => {
const document = ref(null)
const error = ref(null)
let documentRef = projectFirestore.collection(collection).doc(id)
const unsub = documentRef.onSnapshot(doc => {
if(doc.data()) {
document.value = {...doc.data(), id: doc.id}
error.value = null
} else {
error.value = "Document does not exist"
}
}, err => {
console.log(err.message)
error.value = 'Couldn't get the document'
})
watchEffect((onInvalidate) => {
onInvalidate(() => unsub());
});
return { error, document }
}
export default getDocument