Search code examples
restvue.jsaxiosvuex

Vuex and axios, remote content not showing on initial page load


been banging my head against this one for a day or so and need you to my rescue now.

I am building a rest-api driven vue.js site. I am using vuex-rest-api to get data form a copy of wordpress and then output it on the page.

The issue is my data doesn't display on load, throwing an error Error in render: "TypeError: Cannot read property 'title' of undefined", . Once I start making changes to the code and webpack does a hot reload on save the content shows. It looks like the data is not available on page load. I can't work out with my current knowledge how to fix this.

I tried different lifecycle hooks ( such as beforeCreated()) for getPosts() but it didn't help.

Here is the code.

posts.js import Vapi from "vuex-rest-api"

const pages = new Vapi({
  baseURL: "http://localhost:8888/wp-json/wp/v2",
  state: {
    pages: []
  }
})
.get({
  action: "getPosts",
  property: "pages",
  path: "/pages"
})
.getStore()


export default pages

Home.vue

<template>
    <div class="container header header--home">

    <h2 v-for="item in title" :key="item.id" v-html="item"></h2>
    <p v-for="item in content" :key="item.id" v-html="item"></p>

</div>
</template>

<script>

import { mapState, mapActions } from 'vuex'
export default {
  created() {
    this.getPosts()
  },
  computed: mapState({
    content: state => state.posts.pages[0].content,
    title: state => state.posts.pages[0].title,
  }),
  methods: {
    ...mapActions([
      "getPosts",
    ])
  }
}

</script>

Solution

  • You have miss type mapState with posts, but there is no posts property. L18-19 of your Home.vue file There is a miss interpretation of type, between pages as Array and content/title as String. L4-5 of your Home.vue file

    Home.vue

    <template>
       <div class="container header header--home">
          <div v-for="item in pages" :key="item.id">
             <h2 v-html="item.title"></h2>
             <p v-html="item.content"></p>
          </div>
    
       </div>
    </template>
    
    <script>
       import { mapState, mapActions } from 'vuex'
       export default {
          created() {
             this.getPosts()
          },
          computed: {
            ...mapState({
              pages: state => state.pages
            })
          },
          methods: {
             ...mapActions([
                "getPosts",
             ])
          }
       }
    </script>