Search code examples
vue.jsvuex

How to return a value from store (vuex) vuejs


I am working on a project (just personal) and trying to get a bit familiar with vuex. I managed to do a lot (so far) but there is one nut I cannot crack.

I am trying to access a field -> salary of a particular employee

Here is my store.js (vuex)

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export const store = new Vuex.Store({
  state: {
      emps: [
              {name: 'John', salary: 110},
              {name: 'Jimmy', salary: 80}
      ],
  },
  getters: {
  },
  mutations: {
    getCurrentSalary: (state, data) => {
      var empIndex = findEmpIndex(data);
      console.log(state.emps[empIndex].salary); // this is ok!!
      return state.emps[empIndex].salary;
    }
  },
  actions: {
    getCurrentSalary: ({commit}, payload) => {
      commit('getCurrentSalary', payload);
    }
  }
});


// helpers
function findEmpIndex (stockName) {
   return store.state.markets.findIndex(item => item.name === stockName);
}

in a component of a particular employee, I am calling it as follows:

<template lang="html">
  <div class="container">
     Current Salary: {{ getCurrentSalary("John") }}
  </div>
</template>

<script>
  import {mapActions} from 'vuex'

  export default {
      methods: {
        ...mapActions([
          'getCurrentSalary'
        ])
      }
  }
</script>

<style lang="css" scoped>
</style>

But there is a catch that the salary can change so I want to get the change instantly (whenever it happens)

I can see the console log correctly (this at least means that function is being called .. but when printed it says:

Current Salary: [object Promise]

It doesn't want to print the value but prints a promise instead .. I did a lot of searching but didn't find (or maybe understand) how to fix this ... if there is any forum or question similar to this one with a solution please send a link (and sorry)


Solution

  • I already solved it with getters :) the only trick was that to return a value (based on the passed parameter) is to return a function inside the getter :)

    getters: {
        getSalary: (state, getters) => (empName) => {
          var empIndex = findEmpIndex(empName);
          return state.emps[empIndex].salary;
        }
      }
    

    and calling it as follows (in the component):

    <template lang="html">
      <div class="container">
          Current Value: {{ getSalary(emps.name) }} 
      </div>
    </template>
    
    <script>
      import {mapGetters} from 'vuex'
    
      export default {
          computed: {
            ...mapGetters([
              'getSalary'
            ])
          }
      }
    </script>
    

    and it reacts to the changes in the salary online/realtime :)

    thx guys