Cannot read properties of null (reading 'find')

Viewed 520

Hello I am a beginner in JavaScript and Vue.js but trying to make some apps to understand how it works. I am following this article to create a sample application. https://morioh.com/p/39a413935071

I could fetch data from the API yet there are some errors in the console in the next step. Here is my code and my console error. Could you please explain why I get this error and how to fix it?

Index.html

<div class="container" id="app">
    <h3 class="text-center">VueNews</h3>
    <div class="row" v-for="posts in processedPosts">
      <div class="columns large-3 medium-6" v-for="post in posts">
        <div class="card">
          <div class="card-divider">
           {{ post.title }}
          </div>
          <a :href="post.url" target="_blank"><img :src="post.image_url"></a>
          <div class="card-section">
            <p>{{ post.abstract }}</p>
          </div>
        </div>
      </div>
    </div>
  </div>

main.js

const NYTBaseURL = 'https://api.nytimes.com/svc/topstories/v2/';
const ApiKey = 'MyApiKey';

function buildUrl(url) {
  return NYTBaseURL + url + '.json?api-key=' + ApiKey
}


const app = new Vue({
  el: '#app',
  data: {
    results: []
  },
  mounted() {
    this.getPosts('home')
  },
  methods: {
    getPosts(section) {
      let url = buildUrl(section)
      axios.get(url).then((response) => {
        this.results = response.data.results
      }).catch(error => {
        console.log(error)
      })
    }
  },
  computed: {
    processedPosts() {
      let posts = this.results

      // Add image_url_attribute
      posts.map(post => {
        let imgObj = post.multimedia.find(media => media.format === 'superJumbo')
        post.image_url = imgObj ? imgObj.url: 'http://placehold.it/300x200?text=N/A'
      })

      // Put Array into Chunks
      let i, j, chunkedArray = [], chunk = 4
      for (i = 0, j = 0; i< posts.length; i += chunk, j++) {
        chunkedArray[j] = posts.slice(i, i+chunk)
      }
      return chunkedArray
    }
  }
})

Console enter image description here

1 Answers

The problem is not all posts have a multimedia array. Some have multimedia: null, and null doesn't have a find method. Only arrays (and other iterables) do.

In short, you might want to replace

let imgObj = post.multimedia.find(media => media.format === 'superJumbo')

with

let imgObj = (post.multimedia || [])
   .find(media => media.format === 'superJumbo')

If post.multimedia is null, it will search in an empty array, which has a .find method, so your app doesn't break.

Related