Search code examples
statenuxt.jsvuexdayjs

Why can I use dayJS in vuex actions but not to initialize states in a Vuex store?


I'm trying to set the initial month to the current month in state using the NuxtJS dayjs module.

Why can I use this.$dayjs in actions but not in state? Shouldn't it be globally accessible?

And how could I initialize the current month in state?

export const state = () => ({
  month: this.$dayjs().startOf('month'), //THIS LINE DOESNT WORK
})
export const mutations = { }
export const actions = {
  bindOngepland: firestoreAction(function ({ bindFirestoreRef, rootState }) {
    const month = this.$dayjs().startOf('month') // THIS LINE DOES WORK
    const nextMonth = state.month.add(1, 'month')
  }),
  setNextMonth({  }) {
  },
}

In this simplified example, I get an undefined error for line 2. this seems to be undefined.


Solution

  • The state is setup while the app instance is created, so the Nuxt instance wouldn't be defined yet. And this "works" (i.e., is your Nuxt instance) in the bindOngepland action because it's a regular function that has its context bound upon being called.

    A workaround is for the component to call an action that initializes the state. In universal mode (or ssr: true), the store can provide a nuxtServerInit action that is automatically invoked to initialize the state:

    // store/index.js
    export const actions = {
      nuxtServerInit({ commit }) {
        commit('SET_MONTH', this.$dayjs().startOf('month'))
      }
    }
    
    export const mutations = {
      SET_MONTH(state, value) {
        state.month = value
      }
    }
    

    In SPA mode (ssr: false), you'd have to dispatch the action explicitly:

    // store/index.js
    export const actions = {
      init({ commit }) {
        commit('SET_MONTH', this.$dayjs().startOf('month'))
      }
    }
    
    export const mutations = {
      SET_MONTH(state, value) {
        state.month = value
      }
    }
    
    // MyComponent.vue
    export default {
      mounted() {
        this.$store.dispatch('init')
      }
    }