What is the best way to incorporate the latest value into the state during mutations?

Check out this code snippet I have:

export default new Vuex.Store({
    state: {
     bottles: 20,
     disabledBtn: false
    },
mutations: {
REMOVE_BOTTLES(state) {
  if (state.bottles > 0) {
    state.bottles--;
  }
},

ADD_BOTTLES(state, items) {
  state.bottles = state.bottles + items
  }   
},
actions: {
removeOneBottle ({commit}) {
  commit('REMOVE_BOTTLES');
},
addBottlesInput ({commit}, items) {
  commit('ADD_BOTTLES', items);
  }
 }
})

I am looking for a solution to update the state with the newly entered value. The mutation adds numbers received as strings, but I would like it to process numerical values passed through the input field. Any help on this matter would be highly appreciated.

Answer №1

In case your problem is that the variable items is being treated as a string instead of a number, you can modify your ADD_BOTTLES mutation like this:

ADD_BOTTLES (state, items) {
  let num = parseInt(items, 10)
  if (!isNaN(num)) {
    state.bottles += items
  }
}

If you are receiving the input from a user through a form, you may want to use the .number modifier. Here's an example based on your provided screenshot...

<template>
  <section>
    <p>Total number of bottles:</p>
    <p>{{ bottles }}</p>
  </section>
  <section>
    <p>How many bottles of water do you want to add?</p>
    <input type="number" v-model.number="items" min="0">
    <button @click="addBottles(items)">Add</button>
  </section>
</template>
import { mapState, mapMutations } from 'vuex'

export default {
  data: () => ({ items: 0 }),
  computed: mapState(['bottles']),
  methods: mapMutations({
    addBottles: 'ADD_BOTTLES'
  })
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Running JavaScript code on a webpage using Selenium

I'm currently developing an automated script to enter a person's address details on a webpage. It's important to note that I did not create this webpage myself. While filling in the address details, I encountered an option to select the coun ...

Is there a way to verify the authenticity of a survey depending on the types of form elements used

Creating a form in PHP with various dynamic form elements like radio buttons, text fields, and dropdowns. Seeking to validate this form using JQuery based on the question type, which is identified by the names q1, q2, etc. $(function(){ if ($(&apo ...

Encountering problems with ajax technology

As a newcomer to Laravel and Ajax, I am facing an issue with displaying the state of the selected country in a dropdown list. Although the data is successfully fetched from Laravel and received through Ajax, I am struggling to dynamically add it to the H ...

Steps for setting an array of ObjectIds in Mongoose

Running tests on the fixture population in mongoose. const mongoose = require('mongoose') const { ObjectId } = require('mongodb'); const app = require('express')() mongoose.connect('<connection fine>', { useN ...

Show the components only if the final digit in their identification number is less than i

I have several span elements with IDs like "tag1", "tag2", etc. I want to display only the spans whose ID ends with a number less than 19. These elements are part of a class called "notVis", which is hidden by default using $(".notVis").hide(); when the ...

Only trigger the function for a single bootstrap modal out of three on the current page

I'm facing a challenge on a page where I have 3 bootstrap modals and I need to trigger a function only for one modal while excluding the other two. $("body").on("shown.bs.modal", function() { alert('modal Open'); //this alert should ...

What is the recommended TypeScript type for the NextJS _app.tsx Component and pageProps?

Take a look at the default _app.tsx code snippet from NextJS: function MyApp({ Component, pageProps }) { return ( <Component {...pageProps} /> ) } The issue arises when transitioning to TypeScript, as ES6Lint generates a warning indicating t ...

Error: Attempting to access properties of an undefined object (specifically 'query')

My productController.js const Product = require('../models/product'); const ErrorHandler = require('../utils/errorHandler'); const catchAsyncError = require('../middlewares/catchAsyncErrors'); const APIFeatures = require(&apo ...

Unlocking the secrets of the Fibonacci function through mathematical equations

Looking for a better way to calculate the fibonacci function using a mathematical formula. I've tried the following formula without success: fib(n) = ((1 + 5^0.5) / 2)^n - ((1 - 5^0.5) / 2)^n / 5^0.5 const fib=(n)=>{ return ((1+(5**0.5))/2)* ...

POST data not being sent via AJAX

I am trying to use AJAX to submit form data to a PHP function, but it seems like the data is not being transmitted. Here is the code for the HTML Form: <form onSubmit="return registration();" id="registration_form"> <input type="email" id="e ...

Encountering a SyntaxError with @font-face while utilizing the typeface-nunito-sans and @poi/plugin-vue-static

I have been working on a static app using Vue, Poi, @poi/plugin-vue-static, and typeface-nunito-sans. Everything seemed to be running smoothly until I encountered a Syntax Error during the build process: project/node_modules/typeface-nunito-sans/index.css ...

Changing a complex object within a nested array of a BehaviorSubject

I'm currently working on an Angular app. Within my service, DocumentService, I have a BehaviorSubject that holds an array of Documents. documents: BehaviorSubject<Document[]> Let me provide you with some insight into the various classes I' ...

JavaScript inserted into debug console by developer

Is there a method to troubleshoot code that has been added through the firefox developer console terminal? For example, I added document.onkeydown = function(event) { // code logic for checking keys pressed } If only I could determine which .js file t ...

The system encountered an internal server error when attempting to locate and import the file

I seem to be having trouble loading components. I'm not sure what I missed connecting somewhere. <template> <MainLayout></MainLayout> </template> <script setup> import MainLayout from "../layouts/MainLayout.vue&qu ...

How to refine a schema by applying filters from another schema

I am working with 2 different Schemas const mongoose = require('mongoose'); const Schema = mongoose.Schema; const {ObjectId} = mongoose.Schema; const matchList = new Schema({ user:[{ type: ObjectId, ref:'User' } ...

Is it possible to send an entire HTML table to the server and then update the database table with it?

Recently, I encountered an issue that has me stumped. Suppose I have a database table A with multiple columns and the server (PHP script) renders this data into an HTML table for the web client. Now, the challenge lies in allowing users to add/delete rows ...

Invoke a C# function (returning a string) within ASP.NET to set the source attribute for an HTML element

I have developed some C# Methods that return a string output, such as "C:/tracks/audio1.mp3", and I want to use this as a reference for my ASP.NET project. Now, I am trying to incorporate my method "GetTrackPath()" into the HTML audio tag so that the meth ...

Encountered an error with @angular-cli/ast-tools during the installation of angular-cli on a Mac running OS X (El Capitan

While attempting to install the latest version of @angular-cli on my Mac OS X (El Capitan) using the command sudo npm install -g @angular-cli@latest, I encountered the following error: Darwin 15.4.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" ...

implementing a new class for event handling that includes the toggleClass function

I'm not a full-time jQuery or JavaScript developer, so please forgive me if this is a silly question. I believe I require something similar to the live function for swapping classes in order to handle the values associated with a selector. This is th ...

Tips for ensuring your jQuery events always trigger reliably: [Issues with hover callback not being fired]

My background image animation relies on the hover callback to return to its original state. However, when I quickly move the mouse over the links, the hovered state sticks. I suspect that I am moving the mouse off before the first animation completes, caus ...