In Lightning Web Components, there seems to be an issue with the splice method not functioning correctly when used with an @api

When checking the console, I noticed that this.unselectedPlayerList.length is not displayed until after using the splice method. This has raised some doubts in my mind about how the splice method works.

export default class MakeYourTeamChild extends LightningElement {
    @api unselectedPlayerList=[];
    SelectPlayer(event)
    { 
        for(let index = 0 ; index < this.unselectedPlayerList.length; index++)
        {
            if(this.unselectedPlayerList[index].Name == event.target.title)
            {
                this.selectedPlayer = this.unselectedPlayerList[index].Name;
                this.unselectedPlayerList.splice(index,1);
                console.log('After Splice',this.unselectedPlayerList.length);
            }
        }
    }
}

Answer №1

According to my analysis, it is not possible to modify the @api variable using splice(), push(), or concat() methods. In order to make changes, you will need to create a duplicate of the @api variable and apply your operations on that duplicate instead. Once the desired modifications are done, assign the duplicate back to the original @api variable. Refer to the code snippet below for guidance:

export default class MakeYourTeamChild extends LightningElement {
    @api unselectedPlayerList=[];
    **let tempUnsltPlList = [];**
    SelectPlayer(event)
     { 
        for(let index = 0 ; index < this.tempUnsltPlList.length; index++)
         {
            if(this.tempUnsltPlList[index].Name == event.target.title)
             {
                this.selectedPlayer = this.tempUnsltPlList[index].Name;
                this.tempUnsltPlList.splice(index,1);
                console.log('After Splice',this.tempUnsltPlList.length);
              }
         }
       **this.unselectedPlayerList = [...tempUnsltPlList];**
    }
}

I believe this explanation clarifies the process. If you find it helpful, please consider marking it as the best answer. Don't hesitate to contact me if you have any further questions!

Answer №2

You seem to be facing a communication issue between parent and child components. The recommended approach is "props down, events up", which helps in understanding how and when a variable changes within a component without affecting the behavior of its child components.

In your scenario, the unselectedPlayerList is a prop in the child component passed from its parent. This means that the parent component owns the data and controls the value of this prop. If the child component needs to modify this value, it should emit an event to instruct the parent component on what to do.

Here is an example of handling this in the parent and child components:
ParentComponent code:
export default class ParentComponent extends LightningElement {
  unselectedPlayerList = []

  handleSelectPlayer (event) {
    const playerName = event.detail.playerName
    const playerIndex = this.unselectedPlayerList.findIndex(player => player.Name === playerName)

    const shallowPlayerList = [ ...this.unselectedPlayerList ]

    shallowPlayerList.splice(playerIndex, 1)

    this.unselectedPlayerList = shallowPlayerList
  }
}
Template code:
<c-child-component
    unselected-player-list={unselectedPlayerList}
    onselectplayer={handlePlayerSelect}
></c-child-component>
ChildComponent code:
export default class ChildComponent extends LightningElement {
  @api unselectedPlayerList = []

  handleSelectPlayer (event) {
    this.dispatchEvent(
      new CustomEvent('selectplayer', {
        detail: {
          playerName: event.target.title,
        }
      })
    )
  }
} 

If you prefer, there is another way to write the parent component using the @track decorator. However, this might impact performance as every modification to the array could trigger a view update.

Feel free to explore these resources for more information:

  • Reactivity
  • Events

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

How to incorporate both image and text links within an HTML div container using JavaScript

I am trying to create a clickable image and text within a div named "films" that both link to the same webpage. However, I am experiencing an issue where only the text link works and the image link is disabled. If I remove the text link, then the image l ...

Implementing JavaScript logic to proceed to the following array within a 3D array once a specific condition is met

I'm currently tackling a challenge that requires me to obtain a specific number using a given 3D array. This array consists of 2D arrays, each containing the same number repeated x times. The parent array is sorted from largest to smallest. Here&apos ...

Regex pattern to replace the zero preceding two times within a string based on distinct criteria

I need to transform the string XY4PQ43 using regex in JavaScript. The output should be XY04PQ0043. Specifically, I want to add a zero prefix to the first number if it is a single digit to ensure it has 2 digits, and for the second number in the string, I w ...

KnexJS Update Error: Failed to perform database update operation

I'm attempting to update a specific line in my database by utilizing Knex's update method. Although the command returns success, I notice no changes reflected in my database upon inspection. Below is the code snippet: async multipleConciliation( ...

Collection of clickable images that lead to creatively designed individual pages

Being relatively new to JavaScript and jQuery, my knowledge is solid when it comes to HTML & CSS. Currently, I have a page with 20 minimized pictures (with plans to increase to 500+ images) that open into a new page when clicked. Although I have no issues ...

Having trouble accessing the height of a div within an Iframe

Here is the issue I am facing: I need my iFrame to adjust its size based on a div within it, but every attempt to retrieve the size of this div results in 0. var childiFrame = document.getElementById("myDiv"); console.log(childiFra ...

Adding color between lines in Three.js

I have two different sets of vertices. One set contains real vertices, and the other set contains the same vertices but with a y value of zero. I am trying to connect these vertices and fill them in but have not been successful so far. I have attempted to ...

Creating a basic bar chart using NVD3 with X and Y axes in AngularJS

I'm currently utilizing the nvd3.js plugin within my angular-js application. I have a straightforward task of creating a bar chart, where bars represent months along the x-axis and revenue values on the y-axis. My goal is to accomplish this using the ...

Is there a way to programmatically fetch files from a MySql / Node.js server?

I've been working on my CRUD app and I'm currently focusing on downloading files from a MySql Nodejs server. Here are the steps I have accomplished so far: I created a function in userContoller.js to query the MySql database for the id=179 (just ...

Skipping certain key-value pairs during the conversion from JSON to Excel Worksheet using the XLSX library in JavaScript

I have a set of objects in JSON format within my JavaScript code and I am looking to transform this data into an Excel worksheet. Within the JSON structure, there are certain key-value pairs that I do not wish to include in the Excel output. For instance, ...

ng-repeat not functioning properly with data defined in XMLHttpRequest

I have a problem with my HTML and AngularJS code. Initially, I defined the list in my controller which worked fine: <li ng-repeat="a in idmasVesselstableList"><a>{{a.table_name}}</a></li> And here is how I set up the controller: ...

Creating a unique custom selector with TypeScript that supports both Nodelist and Element types

I am looking to create a custom find selector instead of relying on standard javascript querySelector tags. To achieve this, I have extended the Element type with my own function called addClass(). However, I encountered an issue where querySelectorAll ret ...

What could be causing my React components to not display my CSS styling properly?

If you're developing a React application and integrating CSS for components, ensure that you have included the style-loader and css-loader in your webpack configuration as shown below: module.exports = { mode: 'development', entry: &apo ...

Load Angular template dynamically within the Component decorator

I am interested in dynamically loading an angular template, and this is what I have so far: import { getHTMLTemplate } from './util'; const dynamicTemplate = getHTMLTemplate(); @Component({ selector: 'app-button', // templat ...

Creating a JavaScript interface for an XML API generated by Rails?

Working with a large Ruby on Rails website has been made easier thanks to the REST support in Rails 2. The site's business logic can now be accessed through a consistent XML API. My goal now is to create one or more JavaScript frontends that can inter ...

The timer will automatically refresh when the page is refreshed

Currently, I am encountering an issue while working on a quiz application in PHP. The problem arises when users start the test and the timer is running correctly. However, when users move to the second question, the timer resets again. Below is the code sn ...

Ways to resolve the angular error "Encountering an unhandled exception: Unable to locate module 'typescript' "?

I'm encountering errors when running ng serve. I've attempted the following code as well, but I'm still facing the same error: npm install -g typescript https://i.sstatic.net/Gyi71.png Error displayed in text format D:\xampp\htd ...

submit django form when a checkbox is checked

tml: <div id="report-liveonly"> <form action="." id="status" method="POST">{% csrf_token %} <p>{{SearchKeywordForm.status}}Only display LIVE reports</p> </form> </div> I am facing an issue while trying to submit ...

Optimal approach to displaying views with Express.js and EJS

Recently, I came across a website that only renders EJS templates using Express.js routing. All the routes are defined in the /routes/index.js file. As the file grows with more routes being added, I am thinking about restructuring it to make it more develo ...

React app is having issues with Hammer.js when used together with touch emulator on touch devices

I've been experimenting with testing touch events using Hammerjs in React, and I'm facing quite inconsistent behavior across different browsers and events. Consider this basic code snippet: import React from 'react'; import PropTypes ...