Improving the efficiency of my conditions in a function with Vue JS

Does anyone have any suggestions on how to optimize this function? I feel like it could be shortened to improve its efficiency. Any help or advice would be much appreciated.

Function:

onStudentActionSelect: function () {
      if (this.selectedRows.length === 1) {
        this.$store.commit(SET_MODAL_OPTIONS, {
          modalContent: MODAL_CONTENT.DELETE_STUDENT(this.selectedRows[0].name),
          modalSettings: MODAL_SETTINGS.CANCEL_DELETE,
          modalCallback: this.deleteStudent
        })
      } else if (this.selectedRows.length > 1) {
        this.$store.commit(SET_MODAL_OPTIONS, {
          modalContent: MODAL_CONTENT.DELETE_STUDENTS(this.selectedRows.length),
          modalSettings: MODAL_SETTINGS.CANCEL_DELETE,
          modalCallback: this.deleteStudents
        })
      }
    }

Answer №1

When it comes to updating your modal, the key lies in determining the content beforehand so that you can make the necessary adjustments before committing to the store. Streamlining code in scenarios like this typically entails identifying the elements that remain constant and organizing the rest using variables or parameters.

onStudentActionSelect: function () {
  // Skip if no selection is made
  if (!this.selectedRows.length) {
    return;
  }

  const modalContent = this.selectedRows.length === 1 ? MODAL_CONTENT.DELETE_STUDENT(this.selectedRows[0].name) : MODAL_CONTENT.DELETE_STUDENTS(this.selectedRows.length);

  this.$store.commit(SET_MODAL_OPTIONS, {
    modalContent,
    modalSettings: MODAL_SETTINGS.CANCEL_DELETE,
    modalCallback: this.deleteStudent
  })
}

Answer №2

Place the condition where the two condition blocks differ:

onStudentActionSelect: function () {
   let value;
   if (this.selectedRows.length === 1) {
         value=this.selectedRows[0].name
       }else if(this.selectedRows.length > 1){
          value=this.selectedRows.length
      }
        this.$store.commit(SET_MODAL_OPTIONS, {
          modalContent: MODAL_CONTENT.DELETE_STUDENT(value),
          modalSettings: MODAL_SETTINGS.CANCEL_DELETE,
          modalCallback: this.deleteStudent
        })
      
    }

Make sure to take into account the scenario when the length is equal to 0, which the ternary operator does not handle.

Answer №3

To simplify handling the if/else statements, you can use the ternary operator as shown in the code snippet below:

onStudentActionSelect: function () {
      this.$store.commit(SET_MODAL_OPTIONS, {
          modalContent: MODAL_CONTENT.DELETE_STUDENT(this.selectedRows.length === 1 ? this.selectedRows[0].name : this.selectedRows.length),
          modalSettings: MODAL_SETTINGS.CANCEL_DELETE,
          modalCallback: this.deleteStudent
        })
    }

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

Creating dynamic HTML elements for each section using JavaScript

Is there a way to dynamically add a task (input + label) for each specific section/div when entering the name and pressing the "Add" button? I attempted to create an event for each button to add a task for the corresponding div of that particular section, ...

Exploring the ins and outs of console interactions in JavaScript

I have come across a problem on Hacker Rank that seems quite simple. The task involves working with N strings, each of which has a length no more than 20 characters. Additionally, there are Q queries where you are provided a string and asked to determine ...

Separate and add on the change validity status of an AngularJS form

If you want to test it out, check this jsFiddle link: HERE (it's recommended to view on a new jsFiddle, refer to the EDIT section of this post) I've noticed what seems like a bug in AngularJS or at least an unexpected behavior. When I detach a f ...

Turn off all VuetifyJS transitions

Is there a way to completely turn off all transitions, such as the slide-x-transition or dialog modal scale transition, in VuetifyJS? ...

Easily fetching data with AJAX through jQuery

Completely new to using jQuery and AJAX, I attempted the code below for a simple http get request: <html> <head> </head> <body> <script src = "jquery-2.1.4.js"></script> <script src = "app.js"></script& ...

Exploring the method to retrieve data on the server side through Express when it is shared by the client within a put request

Here is the angular http put request I am working with: sendPutRequest(data) : Observable<any>{ return this.http.put("http://localhost:5050", data).pipe(map(this.handleData)); } After making this call, the server side method being invoked is ...

Trigger a warning pop-up if a selection has not been made in a dropdown menu using jQuery

I am attempting to display an alert popup when the user fails to select a value from the dropdown menu. Below is my HTML code: <div id="reminder" class="popup-layout"> ... ... </form> </div> In my JavaScript function page, I have tried ...

Troubleshooting React on an Apache Server: A Comprehensive Guide

An interactive React application utilizing React Router has been successfully deployed on an Apache server. After making modifications to the .htaccess file, most of the routes function correctly as intended. Some specific routes within the app rely on us ...

A guide on effectively utilizing the Map datatype in JavaScript

Recently, I've started delving into the world of es6 Map due to its unique features, but I have some reservations regarding pure operations. For example, when removing properties from objects, I usually use the following function: function cloneOmit ...

Attempting to showcase a button element within a popover, although it is failing to appear

I have implemented a feature where a popover appears when hovering over an inbox icon (font-awesome). However, I am facing an issue with displaying a button on the second row within the popover. The title is showing up fine, but the button is not appearing ...

What is the process for running an HTML file on a server that utilizes Cordova plugins?

I'm a beginner in Cordova and recently I created an HTML file which I added to the xampp/htdocs directory and it worked fine. My goal is to create a generic app, but now I want to incorporate the Camera Plug-in into my app. Unfortunately, I am unable ...

Tips for ensuring a consistent highlight for an active link in Bootstrap

Does anyone have a solution for maintaining highlighted links on a web page? <div id="productnav"> <nav> <ul class="nav"> <li><a href="<?php echo $prefix; ?>pages/one.php?category=1" id="navelement1"<?php if ($c == 1) e ...

What is the reasoning behind storing type definitions in the @types namespace within npm?

Have you ever wondered why type definitions in npm are stored under the @types namespace which isn't directly linked to a specific organization, user, or library? Wouldn't it make more sense for npm libraries to have their types located under @[o ...

The functionality of the Bootstrap tabbed pane is not functioning correctly

I am currently in the process of creating a modal tabbed pane in bootstrap following the instructions provided in this guide. You can view the code and functionality on this fiddle. $(document).on("click","#tabs a",function(event) { alert("!!!"); ...

"Trouble encountered while trying to display Angular in an HTML document

In my Angular project, there is a feature where a list of orders is displayed in one view. Each order is represented by its title only. When the user clicks on the title, they should be redirected to a new view showing the complete content of that particul ...

Establishing a global variable in Cypress through a function

My current workflow involves the following steps: 1) Extracting a field value from one page: var myID; cy.get('#MYID'). then(($txt) => { myID= $txt.text(); }) .should('not.equal', null); 2) Mo ...

How to extract a section of a string with AngularJS

Can someone help me figure out how to remove the last part of a string in order to obtain just the main word? For example, turning string(1) into string. Any suggestions would be appreciated! PS. Note that the string might look like this: sringggg(125). ...

Utilize JavaScript to extract content from a text file and showcase it in a Bootstrap modal pop-up through knockout binding

I'm currently working on a function that reads data from a .txt file (located in the website's root directory) and then displays it in a modal dialog box. I believe I've made progress as the file is recognized during debugging, but unfortuna ...

Remove the 'name' attribute from the input tag within the URL

Is there a way to make the server update the URL format to localhost:3000/userinput instead of localhost:3000/?name=userinput when submitting a name? Any suggestions would be greatly appreciated. Thank you in advance. ExpressJs FILE <!DOCTYPE html> ...

Is there a way to alter the data type of a JavaScript object?

Currently, I'm developing a browser-based text adventure game that takes inspiration from classics like Hitchhiker's Guide to the Galaxy and the Zork series. In order to allow players to save their progress, I store important objects such as loca ...