Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to update Vuex state? (MEVN stack)

I am doing a school project and currently I am just trying out Vuex, I want to retrieve a list of workshops from Vuex, but I can’t seem to update my state.

This is my Node backend:

router.get('/all', (req, res) => {
    Workshop.find({})
        .then( workshop => {
            return res.status(201).json({
                workshop: workshop,
                success: true
            })
        })
        .catch( err => {
            console.log(err)
        })
})

This is my result in Postman:
enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is my Vuex store:

import axios from 'axios'

const state = {
    workshop: {}
}

const getters = {
    workshop: state => state.workshop
}

const actions = {
    async getWorkshop({ commit }) {
        let res = await axios.get('http://localhost:5000/api/workshops/all');
        commit('workshop_success', res.data.workshop);
        return res.data.workshop;
    }
};

const mutations = {
    workshop_success(state, workshop) {
        state.workshop = workshop
    }
};

export default {
    state,
    getters,
    actions,
    mutations
}

This is my component:

<template>
    <p>{{ workshop }}</p>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'

export default {
    computed: {
        ...mapGetters(['workshop'])
    },
    methods: {
        ...mapActions(['getWorkshop'])
    },
    created() {
        this.getWorkshop
    },
}
</script>

The problem is, I am able to get the workshop state through Vuex, it displays a simple empty object "{}" (which is the initial state), but it seems like I am unable to trigger the action through the created hook, and the state does not change. If anyone has an idea of what I did wrong, that would be really helpful, because I am really lost right now. Thank you in advance!

>Solution :

state is not a state but context object in mutation, etc parameters. Otherwise commit, etc couldn’t be accessed.

It is:

workshop_success({ state }, workshop) {
    state.workshop = workshop
}

Also this is no-op:

created() {
    this.getWorkshop
},

A function should be called like this.getWorkshop().

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading