Multiplying array elements within the Vuex state with the assistance of Socket.io

I have developed an application using Vue and Vuex that connects to a Node/Express backend with Socket.IO to instantly push data from the server to the client when necessary.

The data sent to the clients is in the form of objects, which are then stored in an array in VUEX. Each object pushed into the array contains a unique string identifier.

This identifier is used to compare the objects already present in the VUEX array. Duplicate objects are not stored, only unique ones are added.

To retrieve the array from VUEX and render components for each object, I utilize ...mapGetters.

However, there seems to be a problem where sometimes the same object is rendered twice even though the VUEX array shows only one copy.

Below is an excerpt of the code from the VUEX Store:

export default new Vuex.Store({
  state: {
    insiderTrades: [],
  },

  mutations: {
    ADD_INSIDER_TRADE(state, insiderObject) {
      if (state.insiderTrades.length === 0) {
        // Add object to the array
        state.insiderTrades.unshift(insiderObject);
      } else {
        state.insiderTrades.forEach((trade) => {
          // Check if the insider trade is already in the store
          if (trade.isin === insiderObject.isin) {
            // Return if it already exists
            return;
          } else {
            // Add object to the array
            state.insiderTrades.unshift(insiderObject);
          }
        });
      }
    },
  },
  
  getters: {
    insiderTrades(state) {
      return state.insiderTrades;
    },
  },

And here is part of the code from App.vue:

mounted() {
  // Establish connection to the server
  this.$socket.on('connect', () => {
    this.connectedState = 'connected';
    this.connectedStateColor = 'green';
    console.log('Connected to the server');
  });
  
  // Handle disconnection
  this.$socket.on('disconnect', () => {
    this.connectedState = 'disconnected';
    this.connectedStateColor = 'red';
    console.log('Disconnected from the server');
  });
  
  // Receive insider trade data and add it to the store
  this.$socket.on('insiderTrade', (insiderObject) => {
    this.$store.commit('ADD_INSIDER_TRADE', insiderObject);
  });
},

Answer №1

Instead of iterating over existing items and adding the new item multiple times, you can use Array.find method to find if the item already exists:

ADD_INSIDER_TRADE(state, insiderObject) {
  const exists = state.insiderTrades.find(trade => trade.isin === insiderObject.isin);
  if (!exists) state.insiderTrades.unshift(insiderObject);
},

No need for the initial check on the length before adding a new item.

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

Combining PHP code within JavaScript nested inside PHP code

I am currently facing an issue with my PHP while loop. The loop is supposed to iterate through a file, extract three variables for every three lines, and then use those variables to create markers using JavaScript. However, when I try to pass the PHP varia ...

Pass the selected ID from a Vue.js select component to an Axios post request and then render another select

Forgive me if this is a silly question, as I am new to Vue.js and JavaScript. I'm having trouble getting the id from one select element and using it in another API to display models in the next select element. The listings are working fine when I hard ...

The iFrame that is generated dynamically becomes null when accessed from a page that has been loaded using JQuery

One issue I am facing is with a dynamically created iframe in regular javascript. It functions perfectly fine when called from a static page using conventional methods. However, when it is being called from a page loaded by jQuery, I encounter an error s ...

Assistance Required for Making a Delicious Cookie

Within my interface, there are two buttons displayed - one is labeled yes while the other is called no. <input type="button" name="yes" onclick="button()"> <input type="button" name="no"> In order to enhance user experience, I am looking to i ...

conversion of text to number using JavaScript

After pulling values from an XML file using JavaScript, I face the challenge of converting a string to an integer in order to perform calculations. To extract data from the XML file, I use the following snippet: var pop = JSON.stringify(feature.attribute ...

I used the `MyWindow=window.open` function to display a pop-up window and then navig

On my webpage (http://localhost:8088/hse/public/explorer), I have implemented two buttons: When these buttons are clicked, a new pop-up window will open at (http://localhost:8088/hse/public/explorer/1) onClick="MyWindow=window.open('http://local ...

Grab the source attribute of the <img> tag (identified by class) across numerous HTML pages

Here is an example: A website has the URL , where xxxx represents an integer between 1 and 1935. On each page, there may be an <img class="thumbnail" src="Images\Robots\{robotname}.png">. However, not all pages have th ...

Initialization of an empty array in Typescript

My promises array is structured as follows: export type PromisesArray = [ Promise<IApplicant> | null, Promise<ICampaign | ICampaignLight> | null, Promise<IApplication[]> | null, Promise<IComment[]> | null, Promise<{ st ...

Tips for concealing select options after choosing with select picker?

Our establishment features three distinct rooms, each offering three identical options that users can choose from. https://i.sstatic.net/Jx4Me.png To illustrate, if a user named John selects option one in the first room, that same option will be hidden w ...

Keeping the header fixed on a sticky div (tocbot)

While working on my website, I decided to implement a Table of Contents section using tocbot. However, I encountered an issue where the Title I added above the table doesn't stay fixed when scrolling. https://i.stack.imgur.com/vCm1K.gif Here's ...

Angular Oops! We ran into a small hiccup: [$injector:modulerr]

I am facing an issue with an angular js error angular.js:36 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.19/$injector/modulerr?p0=app&p1=Error%3A%20…gleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.19%2Fangular.min.js%3A18%3A139) ...

Enhancing HTML through Angular 7 with HTTP responses

Sorry to bother you with this question, but I could really use some help. I'm facing an issue with updating the innerHTML or text of a specific HTML div based on data from an observable. When I try to access the element's content using .innerHTM ...

Tips for retrieving return values from AJAX URL content

As I am writing some code to send data from one page to another through the ajax URL, I encountered an issue where the retrieved values on the previous page are showing as null. The first page code looks like this: <script> function myFunction() { ...

The not-found.js file in Next.js is displaying an empty page rather than showing a 404 error message

My current project involves using Next.js v13.4.19 with the app router mode. However, I seem to be facing an issue with the not-found.js page located in the app folder. Whenever a non-existing route is accessed, it does not render a 404 page as expected. ...

Using Vue Formulate to effortlessly upload multiple images

One of my projects involves using a Vue Formulate component for uploading multiple images to an Express.js backend. Here is the code snippet for the Vue Formulate component: <FormulateInput type="image" name="property_ ...

Is it possible to combine EJS compilation and html-loader in the html-webpack-plugin?

I need the html-webpack-plugin to generate my html using my .ejs template that contains <img> tags. The html-loader can update the image URLs in my <img> tags created by Webpack, so I am including it in my configuration: test: /& ...

using outlines for FontAwesome icons in React Native

I am struggling to use the fontAwesome + icon in the middle of a circle as one item. I have tried placing it inside a circle icon, but it doesn't seem to work properly. import IconFA from 'react-native-vector-icons/FontAwesome'; < ...

Is there a way to automatically redirect a webpage based on the URL that is entered

Looking for a solution where a page checks a typed link upon loading, such as: www.test.com/myphp.php=10 If it detects a specific number, it should redirect to another link. For example: Upon finding www.test.com/myphp.php=10, it redirects to www. ...

How can I pass the value of a variable from one Vue.js 2 component to another?

Here is how I have structured my view: <div class="row"> <div class="col-md-3"> <search-filter-view ...></search-filter-view> </div> <div class="col-md-9"> <search-result-view ...></ ...

Tips for utilizing .env variables within npm scripts

I have set the following variable in my .env file: SHOPIFY_STORE_URL=mystore.myshopify.com Now, I am looking to utilize this variable in an npm script like so: "scripts": { "shopify-login": "shopify login --store=SHOPIFY_STO ...