I'm currently working on a website that utilizes the WordPress API for the backend and nuxt.js for the frontend. However, I am facing difficulties when it comes to displaying data on the frontend as I keep encountering the error message "Cannot read property 'title' of undefined"
Below is the content of my store/index.js file
import axios from 'axios'
export const state = () => ({
posts: [],
pages: [],
})
export const mutations = {
SET_POSTS: (state, posts) => {
state.posts = posts
},
SET_PAGES: (state, pages) => {
state.pages = pages
},
}
export const actions = {
async getPages({ state, commit }) {
if (state.pages.length) return
try {
let pages = await axios.get(`https://domain.dev/wp-json/wp/v2/pages`).then((res) => res.data)
pages = pages.map(({ id, slug, title, content, acf }) => ({ id, slug, title, content, acf }))
commit('SET_PAGES', pages)
} catch (err) {
console.error('getPages', err)
}
},
async getPosts({ state, commit }) {
if (state.posts.length) return
try {
let posts = await axios.get(`https://domain.dev/wp-json/wp/v2/posts?page=1&per_page=100&_embed=1`).then((res) => res.data)
posts = posts.map(({ id, slug, title, content, excerpt, acf }) => ({ id, slug, title, content, excerpt, acf }))
commit('SET_POSTS', posts)
} catch (err) {
console.error('getPosts', err)
}
}
}
The template for my About.vue view is shown below
<template>
<div>
<h1>{{ about.title.rendered }}</h1>
</div>
</template>
<script>
import { mapState, mapActions } from 'vuex'
export default {
name: 'About',
computed: {
...mapState(['pages']),
about() {
return this.pages.find(
(page) => page.slug === 'about'
)
},
},
created() {
this.getPages()
},
methods: {
...mapActions(['getPages'])
},
}
</script>
<style lang="scss" scoped>
</style>
I have replaced the actual API URL with a placeholder in this code snippet but the data is being displayed correctly. You can view a sample of the data below
{
"id": 17,
"date": "2020-12-18T11:36:21",
"date_gmt": "2020-12-18T11:36:21",
"guid": {
"rendered": "https://domain.dev/?page_id=17"
},
"modified": "2020-12-18T11:36:42",
"modified_gmt": "2020-12-18T11:36:42",
"slug": "about",
"status": "publish",
"type": "page",
"link": "https://domain.dev/about/",
"title": {
"rendered": "About"
},
"content": {
"rendered": "<p>Nothing much here!</p>\n",
"protected": false
},
"excerpt": {
"rendered": "<p>Nothing much here!</p>\n",
"protected": false
},
"author": 1,
"featured_media": 0,
"parent": 0,
"menu_order": 20,
"comment_status": "closed",
"ping_status": "closed",
"template": "",
"meta": [],
"acf": [],