Search code examples
javascriptvue.jsvuexnuxt.jscontentful

Why is my Vuex state not changing after nuxtServerInit commit?


I've been using nuxtServerInit to fetch data from my contenful CMS and commit the mutation to add the data to the categories state object. However categories keeps showing empty, even when I try to render it on a component.

I can console.log the data in the mutation function and see the data, why isn't it being pushed into the categories state?

import Vuex from 'vuex'
import {createClient} from '~/plugins/contentful.js' //contentful plugin function

const client = createClient()
const createStore = () => {
  return new Vuex.Store({
    state: {
      categories: {}
    },
    mutations: {
      addCategories(state, data) {
        state.categories += data.items
      }
    },
    actions: {
      async nuxtServerInit(context) {
        client.getEntries({
            content_type: 'category' //fetch everything with the content type set to category
          })
          .then(response => context.commit('addCategories', response))
          .catch(console.error)
      }
    },
  })
}

export default createStore

Solution

  • import Vue from 'vue'
    import Vuex from 'vuex'
    
    import { createClient } from '~/plugins/contentful'
    
    const client = createClient()
    
    export default = () => new Vuex.Store({
      state: {
        categories: {}
      },
    
      mutations: {
        addCategories (state, data) {
          Vue.$set(state, 'categories', [...data.items, ...state.catagories])
        },
      },
    
      actions: {
        async nuxtServerInit ({ commit }) {    
          let response
    
          try {
            response = await client.getEntries({ content_type: 'category' })
          }
          catch (error) {
            console.log(error)
          }
    
          context.commit('addCategories', response)
        },
    })