Learn how to efficiently showcase information extracted from a complex JSON object in VueJS 3 using Vuex

Hello friends,

I've been grappling with this issue for quite some time now, despite following basic tutorials.

In my Vue 3 project, I'm trying to display JSON data. When the data is within an array and I use a loop, everything works fine. However, if the data isn't in an array, I encounter errors or the data gets concatenated together.

Below is the Vuex store I have created:

const region = {
    state: {
        region: {}
    },
    mutations: {
        SET_REGION(state, region) {
            state.region = region
        }
    },
    actions: {
        getAllRegions({ commit }) {
            axios.get("/api/regions/get")
                .then(response => {
                    commit('SET_REGION', response.data)
                })
        }
    },
    getters: {
        getAllRegions (state) {
            return state.region
        },
        getDelegue (state) {
             return state.region.delegue
        }
    }
};

Upon calling this data on my page, I receive the following output:

[
{
  id: 3,
  name: "Occitanie",
  agents: [ ],
  delegue: null
},
{
  id: 2,
  name: "Ile de France",
  agents: [ ],
  delegue: null
},
// More data here...
]

The result appears satisfactory to me. However, when it comes to displaying the data in Vue, I face challenges specifically with the "DELEGUE" data.

<div v-for="region in myFunctionToRetrieveJsonData">
    <p>Name: {{ region.name }}</p> // WORKING

    <p v-for="agent in region.agents">
        {{ agent.lastname + ' ' + agent.firstname }}<br> // WORKING
        {{ agent.phone }}<br> // WORKING
        <span v-for="email in agent.user">{{ email }}</span> // WORKING

        Delegue: {{ agent.delegue.lastname + ' ' + agent.delegue.firstname }} // NOT WORKING

        // THE OTHER WAY
        <p v-for="delegue in region.delegue">
            Delegue: {{ delegue }} // DISPLAY: DURSLEYJake+3309987654321{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="eb8aab8ac58a">[email protected]</a>"} NOT GOOD
        </p>
    </p>
</div>

Encountering the error:

Uncaught (in promise) TypeError: Cannot read properties of null (reading 'lastname')

It seems that while I can iterate over USERS using a v-for loop, accessing DELEGUE directly poses a challenge. Any suggestions or ideas from your end would be greatly appreciated!

Thank you all for your support.

Logan

Answer №1

If my understanding is correct, please review the code snippet below:

new Vue({
  el: '#demo',
  data() {
    return {
      items: [
        {id: 3, name: "Occitanie", agents: [ ], delegue: null},
        {id: 2, name: "Ile de France", agents: [ ], delegue: null},
        {id: 4, name: "Hauts de France", agents: [ ], delegue: null},
        {id: 1, name: "Grand Est", agents: [{lastname: "DOE", firstname: "John", phone: "+331234567890", user: {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e684a684c884">[email protected]</a>"}}], delegue: {lastname: "DURSLEY", firstname: "Jake", phone: "+3309987654321", user: {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="503110317e31">[email protected]</a>"}}}
      ]
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div v-for="region in items">
    <p>Name: {{ region.name }}</p>
    <p v-for="agent in region.agents">
       {{ agent.lastname + ' ' + agent.firstname }}<br> 
       {{ agent.phone }}<br> 
       <span v-for="email in agent.user">{{ email }}</span>
       Delegue: {{region.delegue?.lastname + ' ' + region.delegue?.firstname }}
    </p>
    
  </div>
</div>

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

What is causing the issue with object to JSON conversion not functioning correctly in this particular scenario with Spring MVC?

I have a specific URL that I need to execute: http://localhost:8080/FitiProject/student. The response that I'm expecting should be a JSON string containing the data of a Student object. Below is the code that I am using: package spring.controllers; ...

Trigger the flexslider to load after fetching additional posts using AJAX

I have experimented with various methods, but unfortunately, I have not been able to successfully download the flex slider in the modal window after clicking on the load more button. I am aware that I need to initiate a second request to invoke the script ...

hashSync function needs both data and salt to generate the hash

I can't figure out why I am encountering this issue, I have checked the documentation and couldn't find my mistake. Any suggestions? Error: data and salt arguments required const {create} = require('./user.service'); const {genSaltS ...

One issue encountered in the AngularJS library is that the default value does not function properly in the select element when the value and

In this AngularJS example, I have created a sample for the select functionality. It is working fine when I set the default value of the select to "$scope.selectedValue = "SureshRaina";". However, when I set it to "$scope.selectedValue = "Arun";", it does n ...

Node.js async.series not functioning properly within Express application - response being triggered prematurely

In my Node.js Express application, I am setting cookies from various sources such as the server, Twitter, and a database. These tasks need to be executed in series to prevent callback complications. I am attempting to utilize Async.js to achieve this, but ...

Nested Op.or operations within Sequelize for multiple conditions

Is it feasible to execute multiple operations using Op.or? For instance, when attempting: [Op.and]: { [Op.or]: [{x: 1}, {x: 1}], [Op.or]: [{y}, {y}] } The second Op.or seems to replace the first one. Is there a method to perform a ...

The addition operator cannot be used with the Number type and the value of 1

Encountering an issue where the operator '+' cannot be applied to types 'Number' and '1' buildQuerySpec() { return { PageSize: this.paging.PageCount, CurrentPage: this.paging.PageIndex + 1, MaxSize: '' ...

Step-by-step guide on how to index timestamp type using Knex.js

I'm in the process of indexing the created_at and updated_at columns using knex js. However, when I try to use the index() function, I encounter the following error: Property 'index' does not exist on type 'void' await knex.sche ...

What is the best way to inform the client when a payment system sends a request to my API callback URL?

Currently, I am in the process of developing a website using Vue.JS for the frontend and creating a backend API in the cloud using Node and Express. I am looking to incorporate payment processing with a provider known as Swish. The Swish API involves send ...

Encountering an undefined response while attempting to validate a form using Ajax

I am encountering an issue with my form validation in JavaScript before submitting through PHP. The textarea fields are returning as undefined and the checkboxes are not sending any data. Being relatively new to JavaScript and PHP, I am unsure of what coul ...

I need to know how to retrieve JSON data and showcase it in XCode Logcat. Additionally, I would like to display an alert if the response

I've encountered an issue with getting data from the Web and trying to display it in logcat. I've pasted the code below. Can someone please help me troubleshoot this? Thank you in advance. NSArray *dicAllNetworks = [NSJSONSerialization JSONObjec ...

How can I verify that my information has been assigned to the variable prior to rendering it? (utilizing useRef)

I've encountered an issue with a button that is supposed to appear only when the text within it overflows its parent container. While the functionality works initially, upon refreshing the page, I receive a typeerror message stating "Cannot read prope ...

Having trouble getting Ajax post to function properly when using Contenteditable

After successfully implementing a <textarea> that can post content to the database without needing a button or page refresh, I decided to switch to an editable <div> for design reasons. I added the attribute contenteditable="true", but encounte ...

"Using JavaScript to create a loop that pauses for a function to

If we have a simple one-dimensional array, let's call it: fruits = ["apples","bananas","oranges","peaches","plums"]; We can iterate through it using the $.each() function: $.each(fruits, function(index, fruit) { displayFruit(fruit); }); Howev ...

Exploring the Contrasts: Understanding the Variances of "Query String Parameter" and "Request Payload"

Currently, I am attempting to scrape an ajax site using Scrapy. The specific URL in question is My aim is to extract the store id. I managed to do this by inspecting all XHR requests in Chrome Developer Tools and identifying the one named ("v1?request_typ ...

Utilize Protractor Selenium to extract content from a popup window

Having trouble capturing the text from a popup using Protractor with getText? The HTML structure can be found here. This popup only appears for a few seconds before disappearing. Can anyone assist me in retrieving the text from this popup? To retrieve the ...

Maintaining the footer and bottom section of the webpage

I am facing an issue with the footer on my website . I want the footer to always stay at the bottom of the page, even when I dynamically inject HTML code using JavaScript. The footer displays correctly on the main page , but it does not work as intended on ...

The child element appears to be failing to trigger the function within the parent component

I am facing an issue with a parent component and a child component. I have a function in the parent component that I want to pass to the child for it to use, but when the X button in the child component tries to call the function, it doesn't work. Be ...

Executing Python Parameters in Azure Runbooks

I am currently working on a runbook where I need to parse parameters from the body of a POST request (using Postman). I have referred to this discussion, but unfortunately, I couldn't make it work. Below is the code snippet from my runbook where I tr ...

Enhance your case class using partial JSON data with the help of either Argonaut or Circe

Is there a way to create an updated instance from a case class instance when given an incomplete JSON, with any necessary DecodeJsons implicitly derived? I am looking for a solution using either Argonaut (preferred) or Circe. For example: case class Pers ...