How can I solve "Uncaught TypeError: Cannot read property 'get' of undefined" in the vuex store?
Asked Answered
I

2

2

If I try this .$session.get(SessionKeys.Cart) in my component like this :

    <template>
        ...
    </template>
    <script>
        ...
        export default {
            ...
            methods: {
                add(item) {
                    console.log(this.$session.get(SessionKeys.Cart)
                    ...
                }
            }
        }
    </script>

It works. I success get session cart

But if I try it in the my vuex store like this :

    import { set } from 'vue'
    // initial state
    const state = {
        list: {}
    }
    // getters
    const getters = {
        list: state => state.list
    }
    // actions
    const actions = {
        addToCart ({ dispatch,commit,state },{data})
        {
            console.log(this.$session.get(SessionKeys.Cart))
            ...
        }
    }
    // mutations
    const mutations = {
        ...
    }
    export default {
        state,
        getters,
        actions,
        mutations
    }

There exist error : Uncaught TypeError: Cannot read property 'get' of undefined

How can I solve this error?

Incorporate answered 27/9, 2018 at 4:12 Comment(1)
this.$session is a Vue plugin, you can't access it from Vuex. Pass your session to addToCart action, you can use it from there.Quoth
J
1

You can pass the component this into your dispatch function, called dispatching with a payload. like so:

<template>
    ...
</template>
<script>
    ...
    export default {
        ...
        methods: {
            this.$store.dispatch('addToCart', { data: {}, ctx: this })

            // add(item) {
            //    console.log(this.$session.get(SessionKeys.Cart)
            //    ...
            //}
        }
    }
</script>

import { set } from 'vue'

// initial state
const state = {
    list: {}
}

// getters
const getters = {
    list: state => state.list
}

// actions
const actions = {
    addToCart ({ dispatch, commit, state }, { data, ctx })
    {
        console.log(ctx.$session.get(SessionKeys.Cart))
        ...
    }
}

// mutations
const mutations = {
    ...
}

export default {
    state,
    getters,
    actions,
    mutations
}
Journalistic answered 27/9, 2018 at 15:33 Comment(0)
W
0

you can do this

import Vue from 'vue’

const session = Vue.prototype.$session;

at the top of your store and in your action method

console.log(session.get(SessionKeys.Cart))

this will work

Wendel answered 19/8, 2022 at 20:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.