简体   繁体   中英

Vuex Mutation not updating the State

Working on a Vuejs application whereby I use Vuex for state management between the components.In Vuex store, I have an action that fetches some data from an API (which works fine) then populate it to the state (via a mutation). Next, I pass the updated state to the component using getters.

The problem is there is a problem populating data to the state from the action. In the DOM I have tried fetching via computed property or using the getter but get empty string

Vuex Store

const getDefaultState = () => {
    return {
        clientDeposit: ''
    }
}


//state
const state = getDefaultState();


//getters
const getters = {
    getDeposit: (state) => state.clientDeposit
}

//actions
const actions = {
    fetchClients({ commit}) {

       const clientId ="23"
       axios.post('/api/motor/fetchClients', {
         ClientId: clientId,
        })
         .then((response)=> {
          
          //console.log(response);  //returns data

          const deposit = response.data;
          commit('setIpfDeposit', deposit);
        })
    }
}

//mutations 
const mutations = {
    setIpfDeposit: (state, value) => (state.clientDeposit = value)
}

export default {
    state,
    getters,
    actions,
    mutations
}

Component

<template>
  <div>
        <button onclick="fetchClients()">Fetch Clients</button> 
        Deposit (Via computed property) : {{ fetchDeposit }}     
        Deposit (from getter) : {{ getDeposit }}         
  </div>
</template>

<script>
import { mapGetters , mapActions } from "vuex";
import axios from "axios";

export default {
  name: "",
  data() {
    return {
    }
  },
  computed: {
    ...mapGetters([
        "getDeposit"
    ]),
    fetchDeposit(){
        return this.getDeposit
    },
  },
  methods:{
    ...mapActions([
        "fetchClients"
    ])
  }
};
</script>

<style scoped>

</style>

You need to fetch the data first. Import mapActions from vuex

import {mapActions, mapGetters} from 'vuex';

Bring in the fetchClients method in your component's methods object

methods:{
 ... mapActions(['fetchClients']),
}

Then in your component's created life cycle method call the fetchClients method

created(){
 this.fetchClients();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM