Developing with Nuxt JS and WordPress API results in the error message: "Error accessing property 'title' of undefined"

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": [],

Answer №1

To ensure that the title attribute defaults to an empty string when either about or about.title are falsy, utilize a computed property:

<template>
  <div>
    <h1>{{ title }}</h1>
  </div>
</template>

computed: {
  title() {
    return this.about?.title?.rendered || ''
  }
}

The use of a computed property is necessary in this scenario because Vue does not currently support optional chaining within <template> elements. However, it is successfully transpiled when utilized within a component.

Feel free to substitute '' with any preferred value to be displayed if the component lacks both about and about.title attributes (e.g., '--', '...', etc).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Monitor fetch() API calls and responses in JavaScript

I’m looking to intercept fetch API requests and responses using JavaScript. Specifically, I want to be able to capture the request URL before it is sent and also intercept the response once it has been received. The code below demonstrates how to inter ...

TypeScript Compile Error: The property is not available in the 'IStateParamsService' type

My client project heavily utilizes TypeScript. Currently, I am encountering a technical issue. Within my HTML code, I have an anchor tag as shown below: <a class="btn btn-default mrm" ui-sref="course-detail({courseId: '{{c.Id}}'})">Detail ...

Can you display a simple HTML view?

I am currently working on a Node.js application with Express framework. In my project, I have a 'views' folder containing an 'index.html' file. However, upon trying to load the webpage, I encountered the following error: Error: Cannot f ...

Activate on click using JavaScript

When a link with the class .active is clicked, I want to use a JavaScript function to deactivate any other active links. The structure of the code should be as follows: <ul class="product"> <li><a href="#myanmar" class="active">Mya ...

Insert a new HTML element only if it is not already present

<p id="main_class"> <span class="new_class"></span> </p> In this code snippet, I am attempting to append <span class="new_class"></span> to the element with the id of main_class. If the span element with the class o ...

Ways to display an image for a duration of 3 seconds upon clicking each button

Need help with my HTML/js code. I have a button that should display an image when clicked, but it's not working properly. Here is the code snippet: <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&qu ...

Do you mean using a JSON object as a value?

When creating a JSON object where the value itself is an object, what is the correct way to write it? var data ='{"phone":{"gtd": "080"}}'; OR var data ='{"phone":"{gtd: 080}"}'; This question may seem straightforward. I am curious ...

Snagging bugs from a spawned Node.js process

Consider this scenario where the child process error is not triggered: const spawn = require('child_process').spawn; const childProcess = spawn('tar', ['--wrong-option'], { stdio: 'inherit' }); childProcess.on(&apo ...

Which specific files do I have to edit in order for Laravel to acknowledge a new data type?

Currently, I am honing my skills in Laravel by working on a Laravel Breeze application. One task that I have set for myself is to incorporate a postal code field into the existing User model, including the registration form. To tackle this challenge, I dec ...

The process of obtaining and sending a token from an HTML page while submitting a form request to a Laravel 5 application involves a few key steps

My application consists of the client side being written in HTML and Angularjs, while the server-side is using Laravel 5. Every time I submit my form, I send the models using $http to a route in my Laravel 5 app, but I continuously encounter the error: pr ...

Upgrade the jQuery library to the latest version 3.7.1, an update from the previous version 3.5

Looking to upgrade the jQuery library on my site from version 3.5.1 to version 3.7.1. Need to make sure I address any removed functions to prevent issues. Can anyone provide insights on which functions were removed in these updates? Checked the release no ...

Exploring the capabilities of a VueJS-compatible product tour library

I am currently working on implementing a feature intro tutorial for my web application, similar to what can be done with intro.js. However, I am encountering an issue where nothing seems to happen when using intro.js - no error messages or tour messages ar ...

"Capturing" AJAX requests from Capybara / Selenium - Rails

Is it possible to monitor real AJAX requests in feature specs using Capybara/Selenium while my app is making AJAX calls on specific events like .click? I attempted to utilize the Teaspoon gem, but it seems to only allow access to fixture URLs (as mentione ...

The issue of texpress-session failing to set a cookie in a React application arises when the app is deployed

I'm encountering an issue where I can't establish session cookies in the browser for my MERN stack application. Everything works fine when both the express server and the react front end are running locally, but the problem arises after deploying ...

Upon selecting the "Purchase Now" button, an ajax request will be sent to the "/purchase" route to submit the data

I'm currently working on extracting data from a form that includes radio buttons. My goal is to capture the selected values when the user clicks the "buy now" button. While I am familiar with using React to update state based on input values, I am exp ...

Angular 8 fails to retain data upon page refresh

I have a property called "isAdmin" which is a boolean. It determines whether the user is logged in as an admin or a regular user. I'm using .net core 2.2 for the backend and Postgre for the database. Everything works fine, but when I refresh the page, ...

What is the optimal approach for managing script initialization on both desktop and mobile devices?

I have implemented a feature on my website that can detect whether the viewer is using a mobile device. Additionally, I have created a JavaScript script that adjusts settings based on whether the user is on a mobile device or not. However, I am wondering ...

Issue with static resource fetching when referencing a .js file within an HTML document while using Flask

My HTML file loads my OpenLayers JavaScript file (which displays a map frame) when opened directly. However, when running the HTML from my Flask python app, the JavaScript file/object fails to load (resulting in no map display, just some heading text). I ...

Nested arrays within an array in AngularJS can be displayed using ng-repeat

I am having trouble iterating over arrays within arrays. My goal is to create a vertical menu with button-like functionality, but I'm struggling to make it work. angular.module('NavigationApp',[]).controller('NavigationController&apo ...

Using Vue.js to bind a key to the input attribute of a name field

How can I group the values of "repositories[][name]" under the key value "repositories[key][name]" when the form is submitted? I am struggling to find a way to add the key value. Any suggestions on how to accomplish this function? <tr v-for="(reposito ...