Skip to content
Advertisement

Data rendered on the screen but has error on the console (Firebase with Vue): Uncaught (in promise) TypeError: Cannot read property ‘contents’ of null

I’m trying to get lesson.contents to render on the screen but I have some errors on the console. Here is the code (I’m using Firebase with Vue 3)

<template>
  <AddContent :lesson="lesson" />
  <div v-if="lesson.contents.length"> 
    <h2>{{ lesson.contents }}</h2>
  </div>
  
</template>
 
<script>
import ContentList from "@/components/ContentList.vue";
import AddContent from "@/components/AddContent.vue";
import getDocument from "@/composables/getDocument";
import { ref } from "vue";
 
export default {
  props: ["id"],
  components: { AddContent },
  setup(props) {
    const { document: lesson } = getDocument("lessons", props.id);
 
    return { lesson };
  },
};
</script>
 
<style>
</style>

Then I have this error:

error

What I’m confused is that I’m still able to render lesson.contents on the screen: enter image description here

I’ve been trying a few hours trying to fix it but I could not find out why. I’d really appreciate your help. Thank you!

My getDocument.js code:

import { watchEffect, ref } from 'vue'
import { projectFirestore } from '../firebase/config'

const getDocument = (collection, id) => {

  let document = ref(null)
  let error = ref(null)

  // register the firestore collection reference
  let documentRef = projectFirestore.collection(collection).doc(id)

  const unsub = documentRef.onSnapshot(doc => {
    // need to make sure the doc exists & has data
    if(doc.data()) {
      document.value = {...doc.data(), id: doc.id}
      error.value = null
    }
    else {
      error.value = 'that document does not exist'
    }
  }, err => {
    console.log(err.message)
    error.value = 'problem fetching the document'
  })

  watchEffect((onInvalidate) => {
    onInvalidate(() => unsub())
  });

  return { error, document }

}

export default getDocument

Advertisement

Answer

This line…

let document = ref(null)

initialises document to null. It is only after the onSnapshot callback is executed does it receive a value with the contents property.

To keep your application from throwing…

Cannot read property ‘contents’ of null

you can initialise document with a better default

let document = ref({ contents: [] })
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement