storyblok / storyblok-nuxt

Storyblok Nuxt module
https://www.storyblok.com/tp/nuxt-js-multilanguage-website-tutorial
MIT License
278 stars 44 forks source link

500 Rendering Error Cannot read properties of undefined (reading 'filename') on Asset Field-type #405

Closed studentofcoding closed 1 year ago

studentofcoding commented 1 year ago

So Asset data can't be accessed during New Story creation (1st render), and show "Cannot read properties of undefined (reading 'filename')" but, when we save and reload, it load fine.


Expected Behavior

I should render fine the 1st time.

Current Behavior

It gives the error "Cannot read properties of undefined (reading 'filename')" When a New Story is created.

Steps to Reproduce

(Bug) This is the related feature and error after Story creation

Screenshot 2023-05-12 at 15 01 00

(Working) After the story is saved, it story renders fine (with the section not being rendered as the asset_heading.filename is null or empty)

Screenshot 2023-05-12 at 15 05 09

(Working) This is when there are Image on asset_heading

Screenshot 2023-05-12 at 15 05 32

(Working) This is when the Image is removed

Screenshot 2023-05-12 at 15 08 05

This is the code

<script setup>
let assetSource = "";
if(props.blok.asset_heading.filename === "") {
  assetSource = "";
  console.log("The asset is not set", assetSource);
} else {
  assetSource = props.blok.asset_heading.filename;
  console.log("The asset is placed", assetSource);
}

if(props.blok.asset_heading.filename == null) {
  assetSource = "";
  console.log("The asset is not set", assetSource);
} else {
  assetSource = props.blok.asset_heading.filename;
  console.log("The asset is placed", assetSource);
}
</script>

<template>
<div v-if="assetSource">
    <section v-if="!isVideo" id="bmi-image" class="d-none d-md-block">
      <div class="container">
        <img v-if="assetSource" :src="assetSource" alt="Image" />
      </div>
    </section>
    <section v-else id="bmi-video" class="d-none d-md-block">
    ...
    </section>
  </div>
  </template>
Dawntraoz commented 1 year ago

Hi @studentofcoding, as the blok object is loaded reactively, you need to constantly add a double check on the properties, meaning that in your conditional, you should check the asset_heading availability too, like:

props.blok.asset_heading?.filename

More info about ?. optional chaining -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining. If you need anything else, let me know 💜