Home > Software engineering >  How to update Vuex state? (MEVN stack)
How to update Vuex state? (MEVN stack)

Time:12-10

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

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!

CodePudding user response:

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().

  • Related