Home > Software design >  how can I update the state of my vuex store?
how can I update the state of my vuex store?

Time:01-20

I'm new here so please forgive me if my write is'nt good or the code section... still trying to figure it out.

so I've been trying a lot of forms in order to achieve the result that I want to but with no success...

Basically the app is getting a salary(amount) and there is the total sum in the account(currentSalar) both of them are from type string and not number... I need to find a way to rest the salary from the total sum and obviously update it.

here are some screenshots If anyone could help me please.

   **/index.js** 

import  mutations  from './mutations.js';
import actions from './actions.js';
import getters from './getters.js';

export default {
    namespaced: true, 

    state() {
        return {
            registers: [
                {
                    id: 'user1',
                    currentSalar: '4,400' ,
                    saves: '12,000',
                    currency: '₪',
                    expense: [{salary: '3,000', category: 'Bar:'}]
                },
                {
                    id: 'user2',
                    currentSalar: '100,000',
                    saves: '3,000,000',
                    currency: '$',
                    expense: []
                }
            ]
        }
    },

    mutations,
    actions,
    getters
}

``````````````````````

``````````````````````
**/mutations.js**

export default {
  addRegister(state, payload) {
    const registerToUpdate = state.registers.find(
      (register) => register.id === payload.id
    );

    const expenses = registerToUpdate.expense;  //////* find((expense) => expense.salary === payload.salary) */
    const salary =  expenses.salary;
    let current =  registerToUpdate.currentSalar;

    const newCurrnt = current -= salary;   // should calculate a new value (UPDATE) for the currentSalar by resting the salary
    console.log(newCurrnt);

    expenses.unshift(payload);
  },
};
```````````````````
**/actions.js**

export default {
    addRegister(context, data) {
        const RegisterData = {
            id: context.rootGetters.userId,
            category: data.category,
            salary: data.salary
        }

        context.commit('addRegister', RegisterData);
    }
}

```````````````````````
**/component**

<template>
 <div >
    <h1>Add expense</h1>
    <form @submit.prevent="ReturnCat">
      <section>
        <label for="salary">Ammount: </label>
        <input type="number" id="salary" v-model.number="salary"/>
      </section>
      <section>
        <label for="category">Category: </label>
        <select id="category" v-model.trim="category">
          <option value="Bar: " id="bar">
            Bar & Restaurants
          </option>
          <option value="Shopping: " id="shopping">Shopping</option>
          <option value="Needs: " id="needs">Needs</option>
        </select>
      </section>
      <base-button >ADD</base-button>
      <h4><a href="">Add entery insted</a></h4>
    </form>
  </div>
</template>

<script>
export default {
  props: ["id"],
  data() {
    return {
      salary: null,
      category: '',
    };
  },
  computed: {
    expensePath() {
      return this.$router.replace("/register/"   this.id);
    },
  },

  methods: {
    ReturnCat() {
      const form = {
        salary: this.salary,
        category: this.category
      }
      this.$store.dispatch('register/addRegister', form);
      console.log(this.salary, this.category);
    },

  }
};
</script>

<style scoped>
#salary {
  margin: 1rem auto auto 1rem;
  height: 1.5rem;
  width: 11rem;
}
select,
option {
  margin: 1rem auto 2rem 1rem;
  height: 1.5rem;
  width: 11rem;
}
.btn {
  margin: 0 auto;
  width: 11rem;
}
</style>
`






CodePudding user response:

JavaScript doesn't understand numbers as strings.

When you want to do arithmetic operations (as I guess you do, since you're developing an app having to do with accounting), you must work with numbers:

  registers: [
    {
      id: "user1",
      currentSalar: 4400,
      saves: 12000,
      currency: "₪",
      expense: [{ salary: 3000, category: "Bar:" }],
    },
    {
      id: "user2",
      currentSalar: 100000,
      saves: 3000000,
      currency: "$",
      expense: []
    }
  ]

Even when you're getting this data from a poorly written API which returns numbers as strings, the first thing you want to do is to turn them into numbers, before placing them in the store.

And when you try to cast a string to number (by appending to it), if the string contains thousand separators as commas (or anything that's not a digit, a dot, or a scientific number notation - e.g: '-3e6'), you're going to get back NaN.

See it here:

const num = '1,000,000'

console.log(  num ) // NaN

// strip commas from it:
console.log(  num.replaceAll(',', '') ) // 1000000


And when you want to display the numbers used in the store to the user, if you want to put thousand and decimal separators on them, use Intl.NumberFormat.

CodePudding user response:

solved:)

here is the code:

`
// index.js
import  mutations  from './mutations.js';
import actions from './actions.js';
import getters from './getters.js';

export default {
    namespaced: true, 

    state() {
        return {
            registers: [
                {
                    id: 'user1',
                    currentSalar: 4400 ,
                    saves: 12000 ,
                    currency: '₪',
                    expense: []
                },
                {
                    id: 'user2',
                    currentSalar: 100000,
                    saves: 3000000,
                    currency: '$',
                    expense: []
                }
            ]
        }
    },

    mutations,
    actions,
    getters
}`

`
// mutations.js

export default {
  addRegister(state, payload) {
    const registerToUpdate = state.registers.find(
      (register) => register.id === payload.id
    );
    
    let current = registerToUpdate.currentSalar;
    const expenses = registerToUpdate.expense;

    current -= payload.salary;
    console.log(current);
   
    expenses.unshift(payload);
    registerToUpdate.currentSalar =  registerToUpdate.currentSalar - 
payload.salary;
  },
};`
  • Related