Cant load content – TypeError: Cannot read properties of null (reading 'attributes‘)

Viewed 1417

currently working on an issue and cant figure out why my page throws me an error.

Having this component:

        <JobDetailSectionText
          :variant="tmpl({ red: 1, blue: 4, yellow: 7 })"
          :image-src="
            jobProfile.attributes.imagePractice
            ? $strapi.options.url +
              jobProfile.attributes.imagePractice.data.attributes.url
            : '/static/img/praxisteil.jpg'
          "
          :image-alt="
            jobProfile.attributes.imagePractice.data.attributes.alternativeText
          "
        >

In my content manager in Strapi I changed the „attribute.imagePractice" from required = true to false and now want to, if no file is added to the database show a default image in '/static/img/praxis.jpg‘.

But the console of the page gives me an error "TypeError: Cannot read properties of null (reading 'attributes')

I tried to figure out the source of the problem but the page only works if I add and imagePractice in the backend, it won’t take the default img I tried to declare with the static path.

Any thoughts? Thanks!

2 Answers

You can use optional chaining to check if property is exist

        <JobDetailSectionText
         ...
            jobProfile.attributes?.imagePractice
            ? $strapi.options.url +
              jobProfile.attributes.imagePractice.data.attributes.url
            : '/static/img/praxisteil.jpg'
          "
          ...
        >

@DinhTX solution is good, but note, that you cannot use optional chaining unless it's Vue 3. Read more here.

If you're using Vue version less then 3 you would need to write a computed property for that src attribute value where you'd check if attributes exist. Actually, I'd recommend you to use computed property anyway cause Vue's templates should be more HTML and less JS (not like React).

Example of computed property would be:

computed: {
  jobSrc() {
     const strapiUrl = `${$strapi.options.url}${jobProfile.attributes.imagePractice.data.attributes.url}`
     return jobProfile.attributes?.imagePractice ? strapiUrl :'/static/img/praxisteil.jpg'
  }
}
Related