Defending against - Cannot read property 'text' of undefined

I've recently shared my feelings that I really think prismic should change how they handle null values.

But what I'm concerned with today is to how to actually defend each variable against null, today.

This was suggested in the linked post.

<div>
  {{ $prismic.asText(doc.pricetag || [ ] ) }}
</bdiv>

How do I handle for nulls in these scenarios?

1. <prismic-rich-text :field="doc.description" />

2. <prismic-image :field="$slice.primary.optional_image" class=""/>

3. <h2>{{slice.primary.title[0].text}}</h2>

4. <nuxt-link :to="`/${item.internal_link.type}/${item.internal_link.uid}`">Click Me</nuxt-link>

A quick way would be to use computed properties.

Hey @online,

Thanks for sharing all of your thoughts on this! I read your other post, and it was really well-reasoned. Paulina shared it internally for the product team to consider. As you know, it was a very deliberate choice in the early days of developing Prismic. We published a blog post on our thinking a couple of years ago.

As @marcellothearcane said, computed properties work well here. Here's how I handle this in one of my projects:

<template>
  <div>
    <div v-if="valid">
      <div class="info-box">
        <prismic-rich-text :field="slice.primary.text" />
      </div>
    </div>
    <div v-else>
      <p>
        Warning: Please enter text.
      </p>
    </div>
  </div>
</template>

<script>
export default {
  name: "InfoBox",
  props: {
    slice: Object
  },
  computed: {
    valid() {
      if (
        this.slice.primary.text.length === 1 &&
        this.slice.primary.text[0].text === ""
      ) {
        return false;
      } else {
        return true;
      }
    }
  }
};
</script> 

All text fields would look similar to that. An image field might look like:

  computed: {
    valid() {
      if(this.slice.primary.image){
        return true
      } else {
        return false
      }
    }
  }

I like this approach because it encourages me to deal with errors dynamically. I could, for instance, show warnings to editors when they're previewing content, and then program a fallback for production. With an empty string, I'd be more likely to leave no error handling. Then, if a post got published with an empty title field (for instance) that could cause a cascade of issues that would be worse (in my opinion) than a build error, because it would be harder to detect.

Please let me know what you think, and if you have more questions, or if you'd like more detailed examples. I'm sure I can find some if you'd like.

Best,
Sam

1 Like

You could also do something like this:

computed: {
  image () {
    return this.slice.primary.image || []
  },
  title () {
    return this.slice.primary.text || [{
      "type": "heading1",
      "text": "No title",
      "spans": [],
    }]
  },
}

This issue has been closed as it has been fixed, Flag if it is not the case for you to reopen.