[Vuejs]-How to get updated value from vuex store in component

0👍

Mutations generally are not meant to have a return value, they are just to purely there set a state value, Only getters are expected to return a value and dispatched actions return either void or a Promise.

When you dispatch an action, a dispatch returns a promise by default and in turn an action is typically used to call an endpoint that in turn on success commits a response value via a mutation and finally use a getter to get the value or map the state directly with mapState.

If you write a getter (not often required) then mapGetters is also handy to make vuex getters available directly as a computed property.

Dispatch > action > commit > mutation > get

Most of your setup appears correct so it should be just a case of resolving some reactivity issue:

// content.js

const state = {

  uploadProgress: 0

}

const actions = {

  editContentBlock (context, contentObject) {

    // other code

    .patch(`/contentblocks/${id}/patch/`, contentObject, {

      onUploadProgress: function (progressEvent) {

        context.commit('SET_UPLOAD_PROGRESS', 
          parseInt(Math.round((progressEvent.loaded / progressEvent.total) * 100)));

      },
    }

    // other code

  }

}

const mutations = {

  SET_UPLOAD_PROGRESS(state, uploadProgress) {

    state.uploadProgress = uploadProgress

  }

}

// component.vue

<template>

  <div> {{ uploadProgress }} </div>

</template>

<script>

import { mapState } from 'vuex'

export default {

  computed: {

    ...mapState('content', ['uploadProgress']) // <-- 3 dots are required here.

  }

}

</script>

Leave a comment