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);
});
},