Leveraging Vue computed properties to update local state without the need for Vuex

I need help with filtering a list of people's scores based on different time periods. Each person has a 'scoreHistory' array containing their scores at various points in time, and I want to see the total score for each person starting from 0 say 30 days ago.

My current code is partially working, but it seems to be altering the original data set instead of creating a new filtered version. Here is my code snippet:

filteredScores () {
  if(!this.people) {
    return
  }
  
  let allPeople = this.people.slice(0)
  let timeWindow = 30 //days
  const windowStart = moment().subtract(timeWindow,'days').toDate()

  for (const p of allPeople ) {
    let filteredScores = inf.scoreHistory.filter(score => moment(score.date.toDate()).isSameOrAfter(windowStart,'day'))

    p.scoreHistory=filteredScores
    
    p.score = inf.scoreHistory.reduce(function(sum,item) {
        return sum + item.voteScore
      },0)
  }
  return allInf
}

Although the function calculates the total scores correctly, it seems to be modifying the global state instead of creating a new one. Can someone guide me on how to prevent this unintended alteration?

Thank you for any assistance provided.

Answer №1

The issue at hand is not the modification of the array, but rather the modification of the objects within it. By altering the scoreHistory and score properties of each item in the array, you are affecting the original data. A better approach would be to create a new array using the map method, where each item consists of a copy of the existing object along with an additional score property.

filteredScores () {
  if(!this.people) {
    return
  }

  let timeWindow = 30 //days
  const windowStart = moment().subtract(timeWindow,'days').toDate()

  return this.people.map(p => {
    let filteredScores = p.scoreHistory.filter(score => moment(score.date.toDate()).isSameOrAfter(windowStart,'day'))

    //calculate new score
    let totalScore = filteredScores.reduce(function(sum, item) {
      return sum + item.voteScore
    }, 0)

    // Create a new object containing all the properties of p with an added score property
    return {
      ...p,
      totalScore
    }
  }
})

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

In configuring the print settings, I specified margins to ensure proper formatting. However, I noticed that the margin adjustment only applies to the first page. I need

I have a method that retrieves margin top value from the backend. It works perfectly on the first page of print, but on the second page, the margin top space is missing. initializePrintingSettings() { this.printService.fetchPrintSettings().subscribe(respon ...

Converting Node JS request to an API into React Fetch syntax

I have encountered a problem while developing an app in React-Native that connects with the Hubspot API. Initially, I tried to make the request using the Node JS request module, but it didn't work well with React Native when Expo was involved. Now, I ...

Embedding links in v-bind:href

I inserted a dynamic link inside the <header></header> section using the method mentioned here: Vue JS and appending a variable to end of a URL Below are the relevant codes: <tr class="notice-row" v-for="(myCase, id) in case ...

Is it considered proper to initialize an empty array within the data object of a Vue.js component?

For my component, I am in need of multiple empty arrays and predefined objects. The data object structure provided below seems to be effective for my purpose. However, I am uncertain if this is the optimal pattern and whether it might lead to unforeseen co ...

Steps for adjusting button size in Sencha Touch

How can I resize a button in Sencha Touch 2 to make it smaller? I need to change its height. Any sample code you could provide would be greatly appreciated! Thanks navigationBar: { items:[{ xtype: 'button', ...

How to use AngularJS to collapse various panels with unique content

Hey everyone, I'm working on developing a collapsible panel using Angular. The panel should consist of a header and body to display the content. The desired behavior is that when a button is clicked, the content collapses down, and clicking the same b ...

Avoid having Masonry load all divs simultaneously

I have experience using jQuery Masonry on Tumblr, but now I want to incorporate it into my portfolio website for displaying my photography. However, I'm struggling to find a solution that allows sets of images to load in as the user scrolls to the bot ...

Autofill class names in VS Code for Next.js using Emmet

How can I modify Emmet autocomplete to change from className="" to className={styles.}? If it is possible, could you please guide me on how to achieve this? Alternatively, if modifying the autocomplete feature is not an option, is there a way to create a ...

When the user clicks on the login text field or password field, any existing text will

Currently, I am working on the login section of my website and I would like to implement a similar effect to Twitter's login form, where the Username and Password values disappear when the Textfield and Password field are in focus. I have attempted to ...

What is the proper method for submitting a mail form via AJAX without using jQuery?

Currently, I am working on integrating a PHP mail form with AJAX. The aim is to create a straightforward form that collects user information such as phone numbers and sends it to my email address. While I have managed to set up the form to send emails usi ...

Query CSS to target an empty array within the .data() method

I have a scenario where I am storing an array in a button using Jquery's .data() method. If the array happens to be empty, I want the button to appear in red color. How can I target the button with an empty array using CSS? var values1 = []; var ...

How about creating a customized sorting algorithm from the ground up that incorporates a comparator?

My current assignment requires me to create a unique sorting method from scratch (cannot use Array.sort()) that accepts a comparator and organizes a list based on that comparator. const people = [ {name: 'Bill', age: 30, likes: 'food' ...

The Object filter is experiencing a delay with processing 10,000 items

When an API returns over 10,000 objects in the format of {firstName:'john',lastName:'Cena'}, I am faced with a performance issue. In my parent React component, I make the API call in componentDidMount and pass this object to child compo ...

Is it possible to automatically close the modal by clicking outside of it

How can I make sure that my modal box only closes when clicking outside of it, and not when clicking on the buttons inside? I have a ref to the parent element that successfully closes the modal on click outside, but currently it also closes if I click on t ...

Utilizing environment variables in Vue.js and Azure DevOps for seamless integration

Currently, I am working on a project and utilizing Vue.js for the frontend. While testing locally, everything is functioning as expected with different environment variables set in .env.development and .env.production files. However, I have encountered an ...

Generating a new display div element using an anchor link

I've set up a div container with a button that, upon clicking, adds a class to an element in my markup causing it to expand and take over the entire screen. Markup before: <section class="isi" data-trigger="toggle" data-trigger-class="isi--show-i ...

Tanstack onMutate Callback Fails to Activate Modal on React State Update

Currently, I am in the process of developing a Dapp and I need to incorporate transaction tracking. One issue I am facing is with trying to display a modal window when the approval setting process begins. Despite attempting to alter the isOpen state of the ...

How can the ID of a table row be retrieved if it is selected?

In my datatable, I have a list of Cars where each row contains a Car ID. A checkbox column has been added to the first cell in the table - when checked, the row is highlighted to show the user their selection. The goal is to retrieve the IDs of all selecte ...

"Encountering issues with toggle effect in nested divs when utilizing an Angular Directive -

I have included a link to the Plunker. Unfortunately, I am facing issues with accessing the elements .gc and .mc. On the other hand, the class .bc is functioning properly. My goal is to implement a toggle effect on them based on hierarchy: BroadCategory ...

Timer malfunctioning and failing to count down

I'm having an issue with the countdown timer I created. Strangely, when I use console.log to check the value of count--which initially starts at 3--it shows a negative number like -3498 even after just 15 seconds. This indicates that there might be an ...