Avoiding Repetition in Vue.js with Vuex

When approaching repetitions in my code with Vue.js and Vuex, I often encounter similar mutations that need to be handled separately. For instance, I have mutations for both Services and Materials that share a lot of similarities.

The first mutation is for Services:

function setServiceItem(state, {model, value}) {
  const service = state.order_services
  service[model] = value
  if (model === 'service') {
    service.unit_price = value.price
  }
  updatePrice(service)
}

The second mutation is for Materials:

function setMaterialItem(state, {model, value}) {
  const material = state.order_material
  material[model] = value
  if (model === 'material') {
    material.unit_price = value.price
  }
  updatePrice(material)
}

Although these mutations are very similar, the constraints of Vuex limit my ability to merge them into a single mutation. One potential solution I considered was adding a third parameter like 'location' and handling them within a single function:

function setMisc(state, {model, value, location, eventForPriceAssignment}) {
  const item = state[loc]
  item[model] = value
  if (model === eventForPriceAssignment) {
    item.unit_price = value.price
  }
  updatePrice(material)
}

However, this approach would make the function more intricate and require passing additional parameters, negating the benefits of keeping the code DRY.

Answer №1

In my perspective, I believe that using a more detailed approach is the most accurate way. When utilizing the Vue dev tool, being able to identify the mutation by name can greatly assist in the debugging process. Nevertheless, in situations where I am updating an object with numerous parameters, I have opted for the latter method.

Answer №2

When considering the placement of logic in a mutator method, the key question arises: should it all be contained within one method, or should it be split into separate methods for better organization? My perspective is that a mutator named setMaterialItem should specifically alter the state of a property named materialItem. However, upon closer inspection, it appears to perform various tasks on an object named order_material. How to address this discrepancy depends on the specific objective you are aiming for. It might be necessary to utilize an action, restructure your store into modules, or consider incorporating a mixin for improved code reuse. Without a comprehensive understanding of your app's structure, it is challenging to provide a definitive solution.

Although principles like DRY (Don't Repeat Yourself) are valuable for guiding development, it is equally important to ensure that your app is logically organized, easily maintainable, and comprehensible to you. Strive for a cohesive structure rather than perfection, allowing yourself some flexibility when your code is not flawless.

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

The REACT- Popover feature seems to be having trouble showing the data from my json file

Within the menu/ section, the names of my invited guests are not visible; only the InfoIcon is displayed in the cell. My goal is to implement a Popover feature that will show all the information about the invited guests (including their names and locations ...

What is the best way to fetch an image for application in a vue document?

While working on my portfolio website, I noticed that the assets folder was missing, which is usually present when using Nuxt. To resolve this issue, I manually created an assets folder and added my images to it. However, I encountered difficulty retrievi ...

Ways to retrieve class attributes in a child context

When trying to access the class properties (or methods) from another scope, I find myself having to store it in a local variable within the function scope. class MyClass { constructor(API) { this.API = API; this.property = 'value& ...

Is there a way to create a function that is able to return both a value and a promise

Assume I need to fetch a value only if an object is already present in my model. Otherwise, I should retrieve the output of an endpoint service: model.getDoohkyById = function( id ){ if( this.data ) { if( this.data.length > 0) { ...

Retrieve a single instance of every element within an array using JavaScript

I have an array of player objects, each containing properties such as "position" and "player_name". With 8 unique positions available for players, I aim to extract the first player for each position and transfer them to a new array. This way, the new array ...

How can Angular's as-syntax be used to access the selected object?

When using syntax like ng-options="p.id as p.name for p in options" to select options, I encounter an issue. I require access to the variable p as well. This is necessary for displaying additional labels near inputs or buttons, or even making changes to in ...

How to retrieve the href attribute within an anchor tag using jQuery with a selector based on the div/span ID and the

Hello, I'm new to jQuery and I was hoping someone could help me with extracting the href attribute from an anchor tag using a div or span ID selector along with the anchor tag's class. <span id="view-post-btn"><a href="https://blog.comp ...

Ways to obtain parameter from URL in Express without diving into the request object

const express = require('express'); const app = express(); app.use('/', anyroute); // in anyroute file router.route('/:id').get(controlFunction) controlFunction(req, res, res)=> { // Here we can get the "id" fr ...

Using ASP.NET MVC with JQuery to find the closest HiddenFor value

My current table structure is as follows: <table class="table table-bordered"> @for (var i = 0; i < Model.Count; i++) { <tr> <td width="25px"> @if (!Model[i].Letter.Equ ...

What is the best way to create an answer label box that validates your response?

I am looking to design a question box label that resembles a search box. In this unique setup, users will have the option to input their answer into the question label. For example, if the user types 'kfuffle' as the answer, they will automatical ...

Tips on presenting our data using JSON structure

Hey there! I'm new to Next JS and I'm looking to showcase the data from my index.js file in JSON format in my dynamicid.js file. Can anyone guide me on how to achieve this? index.js In my index.js file, I currently display my output but now I ...

Once the page is refreshed, the checkbox should remain in its current state and

I have a challenge with disabling all checkboxes on my page using Angular-Js and JQuery. After clicking on a checkbox, I want to disable all checkboxes but preserve their state after reloading the page. Here is an example of the code snippet: $('# ...

Utilizing JavaScript to trigger an email with PHP variables included

i am trying to pass a few php variables using a javascript trigger. Everything seems to be working with the variables, databases, and script but I am struggling with the PHP part. Here is my attempt at the PHP code, although it clearly has some issues. I ...

How can a TypeScript Angular directive utilize a function?

Recently, I have been following a unique Angular directive TypeScript pattern that I find really effective. The approach involves giving the directive its own isolated scope by creating a new controller. I encountered a scenario where I needed to invoke a ...

Showing JSON information fetched from an AJAX request within an HTML page

I've been working on a project and I'm almost there with everything figured out. My main challenge now is to display an array of items on a web page after making an ajax call. Below is the code snippet I currently have: JQuery Code: var su ...

Are MEAN stacks and boilerplates suitable for custom applications requiring specialized functionality?

After spending a significant amount of time learning and coding, I have encountered a common issue. You can find the link to the discussion below. Instead of reinventing the wheel, should I utilize existing boilerplates that combine Express, Angular, conn ...

Retrieving CSS properties of an element using JavaScript

How can I efficiently retrieve all CSS rules associated with a specific element using JavaScript? I am not seeking a particular solution, just looking to capture all CSS rules for the given element. For example, consider the following HTML code: <div ...

Newbie problem with MVC Razor: struggling to upload file via Ajax

I am experiencing an issue with my AJAX file upload using C#-Razor. For some reason, when I click the button to submit the file, the controller method is not being triggered. Can anyone provide a solution to this problem? Here is the code snippet: View ...

Adjust the flex box height to match the dimensions of the image container

Currently, I am in the process of constructing a chat message layout and I am facing a challenge where I need to incorporate an image within a text bubble. The width of the bubble is fixed, but the height should adjust based on the aspect ratio of the imag ...

Assigning a value to a hidden field using a Bootstrap radio button

I'm having some difficulty setting the value of a hiddenfield using a Bootstrap radio button. Below is the code for the button group with the radio buttons and the hiddenfield. <div class="myRow"> <div class="smallCol"> ...