Manuel Abascal
Manuel Abascal

Reputation: 6332

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.

Upvotes: 4

Views: 4058

Answers (2)

BigKamil5
BigKamil5

Reputation: 305

Change 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>

With your mapState line you are kinda telling component - 'Hey my store.users are in the getUsers variable' Component do not know about 'users'. You didn't create variable like that.

Another way is to change loop to

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

In that case you can delete computed property 'getUsers'

Upvotes: 2

Kalesh Kaladharan
Kalesh Kaladharan

Reputation: 1058

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>

Upvotes: 6

Related Questions