Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dispatch store action within fetch function in nuxt?

Tags:

I have a project using nuxt universe SSR. I fetch data on layout using fetch method thet trigger store action dispatch. But it doesn't work at all...

Here's the code. This is default layout file:

import Navbar from '~/components/Navbar'

export default {
  components: {
    Navbar
  },
  async fetch ({ store }) {
    await store.dispatch('fetchItems')
  }
}

And here's vuex store:

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

Vue.use(Vuex)

const store = () => new Vuex.Store({

  state: {
    allItems: [],
    currentCategories: []
  },
  mutations: {
    setItems (state, allItems) {
      state.allItems = allItems
    },
    setCurrentCategories (state, currentCategories) {
      state.currentCategories = currentCategories
    }
  },
  actions: {
    async fetchItems ({ commit, dispatch }) {
      try {
        const { data: { items } } = await this.$axios.get('/api/catalog/categories?limit=0')
        commit('setItems', items)
        dispatch('getCurrentCategories')
      } catch (e) {
        console.error(e)
      }
    },
    getCurrentCategories ({ commit }, payload) {
      const newCategories = []
      if (!payload) {
        this.state.allItems.forEach((item) => {
          if (!item.parent_id) {
            newCategories.push(item)
          }
        })
      } else {
        this.state.allItems.forEach((item) => {
          if (item.parent_id === payload) {
            newCategories.push(item)
          }
        })
      }
      commit('setCurrentCategories', newCategories)
    }
  },
  getters: {
    allItems: s => s.allItems,
    currentCategories: s => s.currentCategories
  }
})

export default store

It seems like fetch method doesn't trigger at all. I tried to put something in console.log inside fetch method but I see no output in console... I'm new to nuxt, I used vue before. Any suggestions is highly appreciated.

like image 721
nickstojanovic Avatar asked Jul 21 '20 15:07

nickstojanovic


2 Answers

Do this instead:

async fetch () {
  await this.$store.dispatch('fetchItems')
}
like image 75
Panos Avatar answered Oct 12 '22 21:10

Panos


If the function is not triggered it may be that its path is incorrect. Nuxt recommends using Vuex with modules: https://nuxtjs.org/docs/2.x/directory-structure/store

Each module is namespaced.

So, in your case, I would create an items.js file in the store directory. And, in the layout file, I would trigger the function like this :

store.dispatch('items/fetchItems');
like image 45
kalak Avatar answered Oct 12 '22 21:10

kalak