Create a Vuex Store for Global Data in Nuxt

InstructorJohn Lindquist

Share this video with your friends

Send Tweet

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.

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
~ 6 years ago

I am having the same problem as James.

Eleonora Lester
~ 6 years ago

Same as James

Eleonora Lester
~ 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

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
~ 5 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
~ 5 years ago

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