Preserving reactivity while swapping an item in Vue 3 using the composition API

I am looking to update my object while maintaining reactivity. The variable selectedTime is a Date object, and the function substractMonths will return a new Date object.

<span
   class="calendar__pickable__chevron"
   @click="selectedTime = substractMonths(1, selectedTime)"
   >
   <span>
      <font-awesome-icon icon="chevron-left" />
   </span>
</span>

However, I am facing an issue where Vue 3 is unable to detect the replacement of the object when this operation is performed.

Is there a way to resolve this? (I have used

const selectedTime = ref(new Date())
to create a reactive object).

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

The substract function does indeed return a new Date object.

Excerpt from code: https://gist.github.com/SirMishaa/efb0efe74c6355aabbcb853f7650c22f

My goal is simply to run a function that returns a new date, and replace my selectedTime with the result of that function.

Answer №1

After significant effort, I have successfully resolved the issue and am excited to share the solution.

To illustrate, I have created a simple example: https://codesandbox.io/s/wandering-paper-o952k?file=/src/App.vue

<template>
  <h1>{{ currentTime.toString() }}</h1>
  <button @click="currentTime = addMonths(1, currentTime)">
    Add one month
  </button>
</template>

function addMonths(numberOfMonths, currentTime) {
  const x = currentTime.getDate();
  currentTime.setMonth(currentTime.getMonth() + numberOfMonths);
  console.log(`Function has been called with : ${currentTime}`);
  if (currentTime.getDate() !== x) {
    currentTime.setDate(0);
  }
  return currentTime;
}

Upon investigation, it appears that Vue is unable to detect the change due to returning an object with the same reference as the old object. The key to resolving this issue lies in creating a new object to facilitate change detection.

Instead of using return currentTime;, opt for something similar to return new Date(currentTime) which should yield the desired results.

I hope this explanation proves helpful after my extensive search for a solution.

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

Utilizing the Power of Graphql with NuxtJs

Exploring the integration of GraphQL with NuxtJs. I am facing a challenge as NuxtJs does not offer an option to have a provider in the root element. How can I properly inject the apolloProvider into the root Vue element? Goal: https://github.com/Akryum ...

Using MongoDB to restrict fields and slice the projection simultaneously

I have a User object with the following details: { "_id" : ObjectId("someId"), "name" : "Bob", "password" : "fakePassword", "follower" : [...], "following" : [..] } My goal is to paginate over the follower list using the slice projection operat ...

Using Ajax to insert information into a row of a table

I am looking to update a table with data from a JavaScript function. The table is located in the same .jsp file but not inside the script. Using AJAX <script type="text/javascript"> function searchDetails() { $.ajax({ ...

angularjs controller module reference results in a page that fails to load

I am currently in the process of integrating the angular-wizard module into my Angular application. The Angular app was generated using yeoman. I installed the angular-wizard module using bower install angular-wizard and added it to my index.html file jus ...

Mapped Generics in Typescript allows you to manipulate and

Currently, I am attempting to utilize TypeScript generics in order to transform them into a new object structure. Essentially, my goal is to change: { key: { handler: () => string }, key2: { hander: () => number }, } to: ...

Saving the execution of a function within an array

Creating a JavaScript program where function calls that generate 3D objects will be stored in an array is my current project. Specifically, I aim to include the following function calls: draw_cylinder(0,0,3,2); draw_sphere(0,0,5,3); draw_cone(17,0,7,3); d ...

Issue with resizing causing layout glitches in jsPanel

Greetings and I hope you're enjoying your weekend! I just started working with jsPanel and I've encountered a small issue. Whenever I try to resize the panel, the layout glitches. The shadow disappears and the header becomes abnormally large. I& ...

Eclipse - enhancing outline view by utilizing require.js define(...)

My code is structured within the define(...) function in the following format: define(['angular'], function(angular) { function foo () { console.log("Hi") ; } function foo2 () { console.log("Hi") ...

Error in typing on a prismic application utilizing a ContentRelationshipField

I am facing a type error in my Prismic Next.js application that I am struggling to resolve. While the app functions properly, I keep encountering type errors like the following: The property 'data' does not exist on the type 'ContentRelati ...

Manipulating global state properties within a reducer function in React: How to do it efficiently

I am looking to implement a single loader (backdrop and spinner) within my app component that can be displayed based on the value of a property in the Redux state called showLoader. This loader should be accessible throughout my entire React application. T ...

"An ng-repeat directive with a filter applied results in an empty

After successfully implementing the ng-repeat loop below: <div ng-repeat="einschItem in einschaetzungen.alldata | filter: { savedatum: lolatage[tagarrayindex].tagestring } | orderBy : '-savetimestamp'"> I wanted to check if the filtered r ...

The complexity of JQuery's design has left many puzzled

I am new to using Jquery and I have come to the following realizations: Every selector in Jquery always returns a wrapped list of items, which can be: An empty list A list with a single element A list with multiple elements Chained functions operate o ...

EmberJS - how to register a precompiled handlebars template

In my EmberJS application, I have precompiled all of my handlebars templates so that they are loaded as pure Javascript files. However, I am encountering an issue where these precompiled templates are not being added to the Ember container as expected. In ...

JavaScript's ability to show and hide div elements functions properly in Internet Explorer, but is encountering issues in Firefox and Chrome

I have a total of 20 spans with unique IDs, all set to hidden in my stylesheet. To toggle the visibility of these spans upon clicking on sections of an image map, I created this script: function showDiv(pass) { var divs = document.getElementsByTagName ...

Crafting a Visual Storybook with Express.js

I am currently working on developing a photo album app using MEVN. In this project, the value of req.body.ALBUM is used as the folder name and req.body.DESCRIPTION is designated for describing the content. The issue I have encountered so far is that whil ...

What is the best way to prevent right floated DIVs from interfering with each other's positioning, specifically within a specified space?

Despite feeling like this question may have been asked numerous times before, I've searched high and low for an answer to no avail - both here and on Google. My HTML page has a maximum width that limits the size of the content. This content includes ...

How can I alter the background color while performing a transformation in JS/CSS?

I'm currently working on achieving a flipboard effect for some divs, where one side is white and the other is black. Here's what I have so far: setInterval(function () { document.getElementById('test').classList.toggle('flipped& ...

Retrieve the element at the specified coordinates using the following JavaScript function: `element

Hi everyone, I am currently working on developing a Firefox plugin and have come across an issue with the following function: I am using the code var obj = page.elementFromPoint(x,y); //x,y are the mouse coordinates The problem I am facing is that this f ...

Transferring data between different components in Angular 5

Presently, I am working with two distinct components within my project - a navigation component and a detail component. The navigation component contains several options or items that the user can select. Upon selection by the user, I am attempting to upda ...

JavaScript function to sort an array by indexes specified in a second array

Consider this scenario: I require the capability to rearrange any one-dimensional array so that the new array begins with the center number (if the object count is odd) or the center two numbers (if the object count is even), and then progresses from low t ...