Home > Back-end >  Nuxt is throwing the error 'unknown action type' when I try to dispatch action from vuex s
Nuxt is throwing the error 'unknown action type' when I try to dispatch action from vuex s

Time:10-07

I want to fetch some data from a firebase backend using an action to store it in vuex state. Currently I'm just working with some dummy data. Reading the data from the store in my index.vue works but as soon as I'm trying to get the action in index.vue I get the error that it is an unknown action type.

store/artikels.js

export const state = () => ({
artikel: [
    {
        id: "1",
        titel: "Hallo",
        untertitel: "Servas"
    },
    {
        id: "2",
        titel: "Was",
        untertitel: "Wos"
    },
    {
        id: "3",
        titel: "Geht",
        untertitel: "Wüst"
    }
 ]

})

export const actions = () => ({
   fetchArtikel() {
      console.log('fetch data from firebase')
   }
})

export const getters = () => ({
   artikel: (state) => {
      return state.artikel
   }
})

this is index.vue

<script> 
import { mapActions } from 'vuex'

export default {
  name: 'App',
computed: {
  artikel() {
    return this.$store.state.artikels.artikel
  }
},
async created() {
  await this.$store.dispatch('artikels/fetchArtikel')
}
</script>

I've already tried to put the store in store/index.js without the namespace and also tried to dispatch it via mapActions and async fetch:

import mapActions from 'vuex'

methods: {
  ...mapActions(['artikels/fetchArtikels'])
}

or:

async fetch({store}) {
  await store.dispatch('artikels/fetchArtikels')
}

So far, no luck. Can someone help me out? Thanks in advance!

CodePudding user response:

Try with:

import { mapGetters, mapActions } from 'vuex'

computed: {
...mapGetters(['artikel'}]
},
methods: {
  ...mapActions(['fetchArtikels'])
},
async created() {
  await this.fetchArtikel()
}

CodePudding user response:

The problem is your store's actions and getters are functions, but they need to be objects:

// store/artikels.js
export const actions = () => ({/*...*/}) // ❌ function
export const getters = () => ({/*...*/}) // ❌ function

export const actions = {/*...*/} // ✅ object
export const getters = {/*...*/} // ✅ object

demo

  • Related