Search code examples
javascriptvuejs2nuxt.js

VueJS/nuxt 'state' should be a method that returns an object in store/store.js


I'm new to VueJS and confused about the warning from nuxt:

'state' should be a method that returns an object in store/store.js

So, my store.js contains the following (yes im trying the tutorial from the documentation):

import Vue from 'vue';
import Vuex from 'vuex';


Vue.use(Vuex);
export const store = new Vuex.Store({
  state() {
    return {
      todos: [
        { id: 1, text: '...', done: true },
        { id: 2, text: '...', done: false }
      ]
    };
  }
});

export default store;

Isn't state a method which returns an object? Or did i misunderstood the message?

update:

I also tried the following:

state: () => ({
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ]
}),

But this will give me the same warning.

VueJS/nuxt 'state' should be a method that returns an object in store/store.js


Solution

  • If you are using Nuxt they expect a store/index.js to create a store and the format should be like:

    export const state = () => ({
      counter: 0
    })
    
    export const mutations = {
      increment (state) {
        state.counter++
      }
    }
    

    As you are creating a store/store.js file, that will be treated as a module and might not work as you expect. I strongly recommend to create a store/index.js and follow the docs from Nuxt.