⚠️ This lesson is retired and might contain outdated information.

Create a Vuex Store for Global Data in Nuxt

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 4 months ago

Every application requires data. Nuxt follows the patterns set forth in Vue.js by including Vuex by default. You only need to follow a simple convention to set up Vuex to help your store and access global data in your app. This lesson walks you through setting up the store directory and exposing data to be displayed in your pages.

We'll move this into the store by simply cutting it out, also deleting the Axios dependency, and creating an index file in the store called index.js. We'll just start with a state. We'll export const state, and this is a function which returns an object. We'll call this users.

We'll just make a users array with one object with an ID of zero and a login of John, just to show this working. Then we can access this in our index page by importing from Vuex a helper called mapState. Then we take the computed property in our exported object.

We set it to mapState, and pass in an array of the values we want off the state. Right now, we want the users. Computed doesn't access the data directly. It lets you pass in a method. What we're passing in is mapState, which knows about the store.

Based on the keys you pass in, it will map for the store this users to the users property in this index page. I'll go ahead and run this, NPM run dev. You can see that the only user here is John, because in the store, the only user is John.

To load the data, we'll need a couple more things. We'll need mutations, which is an object, and we'll need actions, which is an object. We'll start with actions, and the method called nextServerInit. This will trigger when the server initializes, and we can tell it to load the data.

I'll go ahead and import Axios from plugins/axios, like we did before. Then I'm going to write this in the async await way. We'll call nextServerInitAsync, what we'll await for axiosGetUsers. This can be the response.

I'll close the sidebar for some more room, then I'll want the users as the response.data. Then I do what's called committing. That's by taking off the...This is a context, and I only need the commit method off of that context.

I'll use that to say setUsers, and then I'll just pass in the users. What this does is triggers something in mutations. Let's add setUsers. This commit is calling this setUsers here, and setUsers takes the state and the users. All it has to do here is say state.users equals users.

Now when I save, you'll see the initial loaded data was the list of GitHub users. Even though I set this as the initial data, this next serverInit ran and committed that data before this data was ever even displayed.

Then you can see in our index page, there's no reference to any sort of data loading or anything. We're just mapping the state on the store, and getting the properties we need. The one we need is called users, which are loaded here, committed here, assigned and updated here.

James
James
~ 6 years ago

Not sure if vuex has changed since this was written but I just get an error when trying this code out: Cannot read property 'state' of undefined

Jeff
Jeff
~ 5 years ago

I am having the same problem as James.

Eleonora Lester
Eleonora Lester
~ 5 years ago

Same as James

Eleonora Lester
Eleonora Lester
~ 5 years ago

Not sure if vuex has changed since this was written but I just get an error when trying this code out: Cannot read property 'state' of undefined

I've copied and pasted the code in the index store:

export const state = () => ({
  users: [{ id: 0, login: "Lele" }]
});

and in the page

<template>
  <div class="f1 code">
    hello world
    <ul>
    <li v-for="user in users" :key="user.id">
      {{user.login}}
    </li>
  </ul>
  </div>
</template>
<script>
import {mapState} from "vuex"
export default {
  computed: mapState(["users"])
}
</script>

Stopped the server and started again and worked.

Kam
Kam
~ 4 years ago

having issue in the 2nd part of this video where you're using async / await to get users using axios.

I can get as far as the below:

import axios from '~/plugins/axios'

export const state = () => ({
  users: []
})

export const mutations = {
  setUsers (state, users) {
    state.users = users
  }
}

export const actions = {
  async nuxtServerInit ({ commit }, { dispatch }) {
    // const response = await axios.get('users')
    // const users = response.data

    // commit('setUsers', users)
  }
}

but the error message i get in the browser isn't really useful:

Request failed with status code 403
node_modules/axios/lib/core/createError.jsopen in editor
 * @param {Object} [request] The request.
 * @param {Object} [response] The response.
 * @returns {Error} The created error.
 */
module.exports = function createError(message, config, code, request, response) {
  var error = new Error(message);
  return enhanceError(error, config, code, request, response);
};

                
 
Js
createError@16:15
Show all frames
events.js:333:22
IncomingMessage.emit
domain.js:485:12
IncomingMessage.EventEmitter.emit
_stream_readable.js:1201:12
endReadableNT
internal/process/task_queues.js:84:21
processTicksAndRejections
Kam
Kam
~ 4 years ago

Odd, turns out you need to kill your dev server and start it again for it to work correctly

Markdown supported.
Become a member to join the discussionEnroll Today