How to dispatch store action within fetch function in nuxt?
Asked Answered
P

2

6

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.

Panther answered 21/7, 2020 at 15:38 Comment(2)
no one helped? did u find the solutions? ThanksBureaucrat
Did you find a solution to this?Nether
E
6

Do this instead:

async fetch () {
  await this.$store.dispatch('fetchItems')
}
Eggers answered 26/4, 2021 at 8:23 Comment(0)
F
1

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');
Frieda answered 11/11, 2020 at 19:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.