How can you iterate over an array of objects that are sent to a component using Vuex Store and a computed property?

I am currently working on a project to familiarize myself with Vuex. As part of this project, I am setting up an array of objects in my store as shown below:

Vuex Store:

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    users: [
      { id: 1, name: 'John Doe', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ff959097919b909abf98929e96">' },
      { id: 2, name: 'Jane Doe', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="771d16191213181237101a161e1b59">' },
      { id: 3, name: 'Mark Greywood', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="91fcf0e3faf6e3f4e8e6fefef5d1">' },
    ]
  },
  mutations: {},
  actions: {},
  modules: {}
});

Next, I am trying to access the state in the component using a computed property like this:

Component:

<template>
  <div class="home">
    <h1>Greetings from the Home component</h1>

   <!-- When I attempt to loop through the users, nothing is displayed --> 
    <div v-for="user in users" :key="user.id">{{ user.name }} </div>

   <!-- However, I can see the users object in the DOM -->
    <div>{{ getUsers }}</div>
  </div>
</template>

<script>
import { mapState } from 'vuex'

export default {
  name: "Index",
  computed: mapState({
    getUsers: state => state.users
  })
};
</script>

<style scoped lang="less'gt;

</style>

I am currently facing some challenges in understanding where I might be going wrong with this implementation.

Answer №1

The current line of code does not grant you access to the users data.

To properly access the list of users, you need to iterate through the getUsers computed property. This property is connected to the users data in the store, ensuring that any changes to the users state are reflected in getUsers. Therefore, it is recommended to iterate through the computed property in your component.

The corrected iteration code should be:

<div v-for="user in getUsers" :key="user.id">{{ user.name }} </div>

Answer №2

Modify this

    <div v-for="user in users" :key="user.id">{{ user.name }} </div>


To this

    <div v-for="user in getUsers" :key="user.id">{{ user.name }} </div>

When using mapState you are essentially informing the component that the store.users data is stored in the getUsers variable, not 'users'. This variable was not previously defined in your component.

Another approach would be to modify the loop to

    <div v-for="user in $store.state.users" :key="user.id">{{ user.name }} </div>

In this scenario, you can remove the computed property 'getUsers'

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

Unlock the potential of JavaScript by accessing the local variable values in different functions

I've been struggling for days to find a solution to this issue... https://i.stack.imgur.com/KDN7T.jpg https://i.stack.imgur.com/tOfCl.jpg The image above illustrates the challenge I'm facing - trying to apply data values from elsewhere to the ...

Component in vue.js vue-gl is missing the camera props

After adding Vue-gl to my app.js like so: const { VglRenderer, VglScene } = require('vue-gl'); Object.keys(VueGL).forEach((name) => Vue.component(name, VueGL[name])); I included a child component in my parent component: <scene :positionI ...

JQuery tips and tricks: How to create a hover effect for an image positioned behind

Is there a way to achieve hover on an element that is positioned behind another? I am working with two images and have come across others with the same issue. However, the solutions they found were just workarounds rather than true solutions to achieving a ...

How can I design a versatile button in HTML/CSS3/jQuery/Javascript that utilizes images for borders and corners for maximum scalability?

Is there a way to create a completely scalable button in HTML/CSS3/jQuery+Plugins using images for borders and corners? I have attempted a messy method, but I am confident that there are more effective solutions available. The approach I considered invol ...

Having trouble with VueJS project not updating after creating a new Docker Image?

What's the deal: I'm currently diving into Docker and decided to work on a small project to learn the ropes. I have a straightforward VueJs Frontend and a basic Python API set up. I successfully created a Docker Volume with 2 containers (1 for t ...

Retrieve information from various MongoDB collections

Greetings! I currently have a database with the following collections: db={ "category": [ { "_id": 1, "item": "Cat A", }, { "_id": 2, "item": "Cat B" ...

Using a for loop, how can the property value be set in another object?

One challenge that I am facing is setting object property values. The object in question looks like this: const newPlan = { name: '', description: '', number: '', monday: { breakfast: '', ...

Attempting to showcase a button element within a popover, although it is failing to appear

I have implemented a feature where a popover appears when hovering over an inbox icon (font-awesome). However, I am facing an issue with displaying a button on the second row within the popover. The title is showing up fine, but the button is not appearing ...

Jquery for controlling the navigation menu

I'm new to JavaScript and facing 3 challenges: 1. When I click on the parent <li>, the correct content of the child <sub> does not show up. Each category like "colors, shapes, sizes" should have corresponding child categories like "green, ...

Combining photos seamlessly and bringing them to life through animation upon window loading

My main goal is to seamlessly fit the images together, but I'm struggling to achieve this. I tried using masonry, but unfortunately it didn't work for me. All I want is to tightly pack the divs together. For instance, in my fiddle example, I woul ...

Angular does not allow the transfer of property values from one to another

As of late, I have delved into learning Angular but encountered an issue today. I have the following Component: import { Component, OnInit } from '@angular/core'; import { SharedService } from '../home/shared.service'; import { IData } ...

Is pl/pgsql block code supported by postgres-nodejs?

I am attempting to define a custom UUID variable that can be utilized across multiple queries within a transaction. Initially, I attempted using a JavaScript variable which ultimately defeated the purpose of declaring the variable on the server side. The ...

Tips for correctly retrieving the current state from a pinia store to use as an argument for an asynchronous function

I am currently facing an issue with a simple counter store in pinia. The counter itself updates and displays correctly on the page, however, when trying to use the count in a specific function, it does not reflect the updated state of the counter store. Ho ...

What steps should I take to address the issues with my quiz project?

I've been working on a new project that involves creating a quiz game. I came across some code online and decided to customize it for my needs. However, I'm encountering some issues with the functionality of the game. Right now, the questions ar ...

How to style focused input using Vue2

I have a form that contains multiple input fields, and I want to dynamically add a class to the label tag of the focused input and remove it when another input is selected. Initially, I tried the following code: onInputSelected: function(e) { var la ...

Ways to verify the presence of an element in a list

I found this interesting JS code snippet: ;(function ($) { $('.filter-opts .opt').click(function(){ var selectedName = $(this).html(); $('.append').append('<li>' + selectedName + '</li> ...

What is the process for determining the date that is 28 days past a specified date?

I need assistance with finding the 28th day from a date formatted as YYYY-MM-DD. I've attempted various methods without success. Ideally, I would prefer a solution that does not involve Moment.js. Check out my code on Jsfiddle If there are no altern ...

What is the best way to update a nested property in an object?

Consider the following object: myObject{ name: '...', label: '...', menuSettings: { rightAlignment: true, colours: [...], }, } I want to change the value of rightAlignment to fals ...

The date picker feature of Jquery Mobile is not appearing on the popup field

I implemented the jtsage jquery mobile date picker, and I am facing an issue where the date picker appears behind the popup instead of in front of it when the text inside the popup is clicked. Here is a snippet of my code: <div data-role="content"> ...

Automatically calculate line total using jQuery when input blurs

Within my interface, I have a section that allows users to input their class information for reimbursement. There are 6 line items available for them to fill out with the cost of books and tuition. Ideally, I would like the user to be able to enter these c ...