Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through an array of objects passed to a component with Vuex Store & a computed property?

I'm building a project to learn Vuex. I'm creating an array of objects in my store like so:

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: '[email protected]' },
      { id: 2, name: 'Jane Doe', email: '[email protected]'  },
      { id: 3, name: 'Mark Greywood', email: '[email protected]'  },
    ]
  },
  mutations: {},
  actions: {},
  modules: {}
});

Now, I'm accesing the state in the component with a computed property like so:

Component:

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

   <!-- I do not loop through the users, nothing shows --> 
    <div v-for="user in users" :key="user.id">{{ user.name }} </div>

   <!-- I get 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">

</style>

I don't understand what I'm doing wrong.

like image 555
Manuel Abascal Avatar asked Jan 26 '23 15:01

Manuel Abascal


1 Answers

You don't have access to users in this line of code

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

Your component only have access to getUsers (the computed property) which is mapped to the store object users. Thus whenever the users state on your store changes, getUser also gets updated. So you should iterate on the computed property in your component.

So, the iteration should be

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

like image 99
Kalesh Kaladharan Avatar answered Jan 28 '23 10:01

Kalesh Kaladharan