3

My vuex mutation seems to not work synchronous. It looks like this:

mutations: {
    computeStatusData(state, status) {
        if (status.active !== true) { return }

        const started = new Date(status.startedAt);
        started.setHours(0, 0, 0, 0);
        const today = new Date();

        status.currentDay = Math.floor((today.getTime() - started.getTime()) / (1000 * 60 * 60 * 24));
        status.currentWeek = Math.floor(status.currentDay / 7);

        if (!status.programm.sections) { console.log('No Sections'); return; }

        for (let i = 0; i < status.programm.sections.length; i++) {
            if (status.currentWeek <= status.programm.sections[i].to) {
                status.currentSection = i;
                console.log('Current Section', status.currentSection)
                break;
            }
        }
        console.log('new status!', status)
    },

In a method of my component I call it like this:

    async loadSections() {

        await somethingElse();

        if (this.status && this.programm.sections) {
            console.log('Recomputing Status')
            this.status.progamm = this.programm;
            this.$store.commit('computeStatusData', status);
            console.log('updated Status', this.status)
        }

        this.$nextTick(() => { this.$forceUpdate(); }) 
    },

My console log looks like this:

Recomputing Status
updated Status {…}
Current Section 0
new status! {…}

If the mutation was synchronous it should log Current Section 0 and new Status! before updated Status but it doesn't.

It doesnt seem to return a Promise because when I do console.log(this.$store.commit('computeStatusData', status)); it just logs undefined.

Jonas
  • 7,089
  • 15
  • 49
  • 110
  • 1
    Isn't it possible that the commit doesn't log (e.g. status is not active). And what you see is another run of the mutation from another place after loadSections() is over? I'd put a log at the beginning of the mutation code just to be sure. – Szellem Apr 12 '19 at 16:15

1 Answers1

2

The correct way of mutate a status is inside an action.

https://vuex.vuejs.org/guide/actions.html

A helpful question: Vuex Action vs Mutations

Eduardo Garcia
  • 249
  • 1
  • 4
  • I tried using the same code in a vuex action which is intented to be called from outside the store as far as I know but I get the same behavior, – Jonas Apr 12 '19 at 15:29
  • 2
    It doesn't answer the question @Eduardo . Putting in actions is just a best practice – Marcelo Apr 12 '19 at 15:30