Search code examples
vue.jswordpress-rest-api

Vue.js 2 + WP REST API "TypeError: Cannot read property 'filter' of null"


I am starting with to learn how to consume the WP REST API using Vue.js 2 and Axion. I manage to initilized a request and show all my posts in a v-for directive. Trying to make a simple filter from the post list that I get from the json request I cannot access to the data:

    var App = Vue.extend({});

   var postList = Vue.extend({
    template:'#post-list-template',
    data (){
        return {
            posts: null
        }
    },

    mounted (){
        axios
        .get('/wp-lab/wp-json/wp/v2/posts?per_page=20')
        .then(response => (this.posts = response.data));
        
    },
    computed: {
      filteredPosts( ) {
        var cat = this.posts;
        console.log(cat);
        return cat.filter( function(post){
            return post.id > 2;
        })
        
                
      }
    }

})

var router = new VueRouter({
  routes: [
    { path: '/', component: postList }
  ]
})

new Vue({
  el: '#mount',
  router: router,
})

I get the error

TypeError: Cannot read property 'filter' of null

console.log(catalogue) shows me all the data retrieved but i cannot aplly a filter property on it. Any ideas what I am doing wrong?

The template goes like this

    <template id="post-list-template">
                <div class="container vue-loop">
                    <article v-for="post in filteredPosts" class="post vue-block">
                        
                        <div class="entry-header"> <h2>{{ post.title.rendered }}</h2> </div>
                        <div class="entry-content"> <img v-bind:src=post.featured_image_src ></img> </div>
                        
                    </article>
                </div>
</template>

Thanks in advance


Solution

  • The computed property filteredPosts is evaluating before posts has been assigned a value by the axios call. So posts is undefined and the call to posts.filter() fails.

    If you add a condition to the computed property that makes sure it's assigned a value before attempting to filter then it will work. See below for an example.

    computed: {
      filteredPosts () {
        var cat = this.posts;
        console.log(cat);
        if (cat) { // ⭐️ check to make sure cat is assigned a value
          return cat.filter( function(post){
              return post.id > 2;
          })
        } else {
          return [] // ⭐️ just return an empty array if cat isnt ready yet
        }
      }
    }