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

4

9

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

Eliathan answered 25/9, 2019 at 7:58 Comment(1)
Not sure which tutorial you're following but your store code seems significantly different from what's described in the Nuxt documentation: nuxtjs.org/guide/vuex-storeWeil
J
21

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.

Judsonjudus answered 25/9, 2019 at 13:56 Comment(3)
ah, ok, now its working without warnings. thank you for the hintEliathan
I don't follow, what do I put in ./store/index.js?Courses
You should put the code above in ./store/index.js.Judsonjudus
U
5

Try this

Use export const store

import Vuex from 'vuex'
import user from './modules/user'

export const store = new Vuex.Store({
  modules: {
    user
  }
})
Undirected answered 2/5, 2020 at 8:40 Comment(1)
That's what I'm doing and I still get this error.Courses
G
0

If you don't want to make a store/index.js then simply replace the state with this syntax, it will remove your warning. It worked for me as well.

export const state = () => ({
  cart: {
    booking: null,
    reservations: [],
  },
});
Goniometer answered 17/8, 2022 at 8:18 Comment(0)
F
0
const getDefaultState = () => {
    return {
        aaa: ""
    }
}

export const state = () => ({
    ...getDefaultState()
})
Finish answered 28/6 at 6:59 Comment(1)
Thank you for posting this answer. While this code may answer the question, might you please edit your post to add an explanation as to why/how it works? This can help future readers learn and apply your answer. You are also more likely to get positive feedback (upvotes) when you include an explanation.Droit

© 2022 - 2024 — McMap. All rights reserved.