Registered arrays in Nuxt.js will show double values when displayed

Identifying the Issue

I'm facing a puzzling situation where array values are being displayed on the screen. Initially, everything seems fine with the correct values showing up. However, after navigating to another page or triggering an event, the displayed values mysteriously double. Oddly enough, upon refreshing the screen, the values revert back to normal. I need help in pinpointing the root cause of this strange behavior and finding a resolution.

https://i.sstatic.net/3adgy.png

Upon first glance at the screen, all values appear accurate. But upon returning from a different link, the values seem to have multiplied. A quick refresh fixes the issue without any errors detected.

https://i.sstatic.net/ALIaR.png

Solution Examination

Flow:

① Launch page

② Fetch values from server using "mounted" method

③ Update state with retrieved value using commit

Template:

<v-col cols="9" class="pl-0">
  <v-sheet height="600">
    <v-calendar
      ref="calendar"
      v-model="value"
      color="primary"
      type="week"
      :events="events"
      :event-ripple="false"
      locale="ja-jp"
      :day-format="(timestamp) => new Date(timestamp.date).getDate()"
      :month-format="(timestamp) => (new Date(timestamp.date).getMonth() + 1) + ' /'"
      @mousedown:event="startDrag"
      @click:event="showEvent"
      @mousedown:time="startTime"
      @mousemove:time="mouseMove"
      @mouseup:event="endDrag"
      @mouseleave.native="cancelDrag"
    >

Script:

computed: {
  ...mapState('schedule', ['events', 'selectedEvent']),

mounted () {

 // ② Get values from the server with mounted

this.$axios.$get(url.SCHEDULE_API)
  .then((response) => {
    let data
    response.forEach((res) => {
      data = {
        id: res.id,
        name: res.name,
        color: res.color,
        start: res.start,
        end: res.end,
        updated_at: res.created_at,
        timed: res.timed,
        long_time: res.long_time,
        post_id: res.post_id,
        post_item_id: res.post_item_id
      }

   // ③ commit to manage the retrieved value with state
      this.$store.commit('schedule/setEvent', data)
    })
  })
},

Store:

export const state = () => ({
// ③ commit to manage the retrieved value with state
events: [],
・
・
・

})
export const mutations = {
・
・
・
setEvent (state, payload) {
  state.events.push(payload)
},
・
・
・


Answer №1

After navigating away from the page and returning, or when certain events occur, I noticed that the values displayed on the screen double...

The array contains the correct values in the store. When you navigated back, the component was re-mounted, triggering another API call which executed the setEvent mutation AGAIN. This resulted in the new data being added to the store, causing the doubling of values.

However, upon refreshing the screen, the values return to normal. I am curious about the root cause of this issue and how it can be resolved.

Refreshing the page creates a new store instance, triggering the execution of the mounted hook in the component and restoring the correct values.


Based on my understanding, it is advisable not to store this particular data in the global store. Instead, this data should remain private to the component and be loaded into the component's state only during initialization.

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

Preventing automatic interpretation of double curly braces within a Script tag in Handlebars

In my development project, I am constructing a visual representation of a database table along with various web application functionalities. The technologies being utilized include node.js, express, mysql, bootstrap, and handlebars. Within my pages.js fil ...

Basic PHP code that retrieves information about visitors, such as screen resolution and country of origin

Let me share a bit about myself, as it might provide some context: I am not a professional coder. I prefer to write HTML and CSS manually using Notepad++ because I appreciate the lightweight, efficient code and enjoy having full control over my files and ...

Vue 3 and Bootstrap 5 seem to be struggling with finding the properties of an undefined 'backdrop'

I am facing an issue with Vue3 (Vite) and Bootstrap 5 while trying to create a modal that can be called by code. The problem arises when I attempt to open the modal from its parent component. Bootstrap has been properly installed and included in my projec ...

Mobile view on Google Maps app

I am currently using Google Map API V3 and for styling, I have integrated Snazzy Maps. I have successfully added multiple markers for different locations and everything seems to be working fine. However, there is an issue with mobile devices where users ne ...

Executing a Node.js HTTP GET request is a breeze

I've encountered an issue while attempting to send an HTTP GET request using Node.js. The request to '/path/to/file?query=string' has failed with the error message: read ECONNRESET Any suggestions on how I can resolve this problem? Thank ...

The Javascript function will keep on executing long after it has been invoked

I am currently facing an issue with calling a JavaScript function within an AJAX call. The progress function below is supposed to be executed every time the for loop runs. However, the problem is that although progress is being run as many times as the for ...

Optimal methods for organizing various perspectives on a one-page website

I am developing an application that incorporates AngularJS and Bootstrap. The current setup involves organizing various views using ng-show, allowing for view changes based on button interactions and the enablement/disabling of ng-show values. Within a si ...

The virtual positioning of list items in React Virtualized

Using React Virtualized in a setup similar to the snippet provided below has raised an issue. A few items are being rendered using a CellMeasurer. The last item, which indicates that more items will be loaded, is not rendering correctly. It has the wrong p ...

Iterate through the list elements by utilizing jQuery

I am working with HTML code that looks like this: <ul class="lorem"> <li>text</li> <li>text</li> <li>hello</li> <li>text</li> </ul> Can someone help me figure out how to loop through ...

"Learn the technique of displaying or concealing a row in a ListView with the help of

I'm currently utilizing an Asp.net Listview for displaying data in a "grid" format. Below is the code snippet: <asp:ListView ID="lvDmr" runat="server" DataSourceID="dsDmr" DataKeyNames="id"> <ItemTemplate> &l ...

Issue on Heroku with Discord.js displaying a "Service Unavailable" message

Encountered a strange error while trying to launch my discord bot on heroku. Previously, I implemented a command handler for the bot to organize commands in separate files but faced multiple code errors. With the help of a member from this community, all e ...

Tips for adding a counter column to a jQuery DataTable

I'm working with a datatable that only shows records in the workflow step = "Waiting", the initial step in the process. My goal is to add a column displaying data like this: If record IDs are [95, 87, 65, 34, 12], the new column would show [5, 4, 3, ...

Incorporating elements with wrapping capabilities in ExtJS

I'm puzzled by what should be a straightforward issue. I am trying to place items (buttons, specifically) on a panel so that they are displayed side-by-side and wrap once they reach the end of the panel... Appreciate any insights, JJ ...

Attempting to retrieve and substitute the final value within an input field by cross-referencing or evaluating it against a different value

Can you help me with a solution for fetching the last value (word or character) in an input box, storing it in a variable, and then replacing it with one of a set of values that match exactly or partially? The items within the bindname-block contain vario ...

Tips for rearranging table columns using drag and drop in react js

I have been experimenting with various libraries to create a drag-and-drop feature for changing table columns order. Here is my current implementation: import React, { useState } from 'react'; import './list_de_tournees.css' const Table ...

What is the best way to merge arrays within two objects and combine them together?

I am facing an issue where I have multiple objects with the same properties and want to merge them based on a common key-value pair at the first level. Although I know about using the spread operator like this: const obj3 = {...obj1, ...obj2} The problem ...

Showing the precise age in years by utilizing the provided 'Date of Birth' selected from the datePicker

Is it possible to retrieve the date entered in the datePicker and use it to populate the current age field in a PHP file using either PHP or Javascript? if ($key == 'currentage') { $group[] = $this->form->createEleme ...

Error in the sequence following Axios subrequest

I am currently working on implementing a search functionality using the Wordpress API. Although I am able to successfully make requests, I am facing an issue where the results are not ordered as expected after my initial request. Let me explain the situati ...

Evaluating the highest value within a continuous stream of data using idiomatic RxJS methods

When it comes to calculating the maximum value of a fixed stream, the process is quite simple. For example: var source = Rx.Observable.from([1,3,5,7,9,2,4,6,8]).max(); However, this only outputs a single value (9 in this case). What I aim to achieve is ...

Displaying a loading image when opening an external link using window.open

When a pop-up is opened through a window.open() function for external sites, I am looking to display a loading image icon for the links. One approach I considered is to show the loading image in a 'div' and retrieve the content of the external s ...