4

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.

2 Answers 2

6

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much saved me hours of pain I didn't know what was wrong. Still a beginner tho'
2

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.