Issues with tracking changes in Vue.js when using reactive variables

After triggering a click event, I am attempting to choose a message from a json file. However, I am encountering an issue where the first click does not seem to select anything. Upon the second click, the selected messages are duplicated, and this pattern continues with each subsequent click.

I believe the problem lies in the following code snippet:

import SelectedItem from "../Interfaces/SelectedItem";

const selectedMessage = ref<MessageInterface | null>(null);

const selectMessage = (message: any) => {
  selectedMessage.value = message;
  SelectedItem(selectedMessage); 
};

The structure of the SelectedItem module is as follows:

 import { watch, Ref } from "vue";

export default function SelectedItem<Type>(selectedValue: Ref<Type>): Type {
  watch(selectedValue, (newVal) => {
    chooseItem(newVal);
  });

  function chooseItem(item: Type) {
    if (item) {
      selectedValue.value = item;
      console.log(selectedValue.value);
    }
  }

  return selectedValue.value; 
}

The rationale behind separating the SelectedItem function is to avoid repetition of logic and code across multiple files.

Here's a segment of the code:

<template>
<div>
  <select v-model="selectedMessage">
    <option value="">Select target number</option>
    <option
      v-for="(message, index) in SMSMessages"
      :key="index"
      :value="message.targetNumber"
    >
      {{ message.targetNumber }}
    </option>
  </select>
  <p>Selected: {{ selectedMessage }}</p>
</div>
</template>

<script setup lang="ts">
import SMSMessages from "../data/sms-messages.json";
import { ref } from "vue";
import SelectedItem from '../Interfaces/SelectedItem'
const selectedMessage = ref<string>("");

selectedMessage.value = SelectedItem(selectedMessage);
</script>

Full code can be seen below:

<template>
  <div>
    <ul>
      <li
        v-for="(message, index) in SMSMessages"
        :key="index"
        @click="selectMessage(message)"
      >
        <p>Body: {{ message.body }}</p>
        <p>Origin Number: {{ message.originNumber }}</p>
        <p>Target Number: {{ message.targetNumber }}</p>
        <p>Direction: {{ message.direction }}</p>
        <p>Message Date: {{ message.messageDt }}</p>
      </li>
    </ul>
  </div>
</template>

<script setup lang="ts">
import SMSMessages from "../data/sms-messages.json";
import MessageInterface from "../Interfaces/MessageInterface";
import { ref } from "vue";
import SelectedItem from "../Interfaces/SelectedItem";

const selectedMessage = ref<MessageInterface | null>(null);

const selectMessage = (message: any) => {
  selectedMessage.value = message;
  SelectedItem(selectedMessage); 
};
</script>

Answer №1

  • Non-eager watchers will only activate when the watched value changes, not during initialization, hence why there is no output initially.
  • Each time you invoke SelectedItem(), a new watcher is created, resulting in multiple outputs later on.

It's important to note that the watcher reacts when selectedMessage.value receives a new value, passing it as the first parameter to the handler. Reassigning the same value to selectedMessage.value essentially does nothing (

selectedMessage.value = selectedMessage.value
). In its current state, removing SelectedItem() entirely would have no impact on the outcome.

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

Utilize different versions of jQuery along with various plugins

I have integrated the AdminLTE Template into my project, which requires jQuery Version 3.X. Additionally, I am using the Flotchart jQuery library, which specifically needs jQuery Version 1.11.3. To handle this conflict, I have implemented the $.noConflic ...

Encountering serialization errors in Keras when trying to convert [ 0 1 2 ... 63] to JSON due to deep learning

I've been facing issues while trying to save my Neural Network as a ".h5" file using Keras. The problem arises when I attempt to serialize the model. The error message reads as follows: TypeError: Unable to serialize [ 0 1 2 3 4 5 6 ... 63] to ...

Retrieve a byte array from ASP.NET controller class

I'm working on a Controller class (using C#) that needs to return a byte array from its login method. Below is the source code for my Login functionality within the Controller class: [RoutePrefix("Account")] public class AccountsController : ApiC ...

What is the best way to display images when a single element in a list created by ngFor is hovered over in Angular 2

displayStar(val) { this.starDisplayed = true; } <ul class="listboxtickets"> <li class="selectlistticket" *ngFor="let item of ticketList" (mouseover)="displayStar(item.id)" (mouseleave)="hideStars()"> <div class="ticket ...

Transferring cookies across subdomains

I am facing an issue with an ajax request going from one subdomain to another, for example from sub1.example.com to sub2.example.com. Despite having a cookie set for all domains (cookie domain='.example.com'), the cookie is not being sent to the ...

Expressjs - Error: Headers already sent to the client and cannot be set

After testing various solutions from others, I am still unable to resolve this error. My objective is to iterate through each item in the array sourced below: novel.ts export let indexList = (req: Request, res: Response) => { novel.getAllDocuments ...

Find the calculated values within an Angular Material table

I came across this fantastic example of an Angular Material table with checkboxes that fits perfectly with what I want to implement in my application. However, I am facing a challenge - I need to calculate the total value of the checked rows. Specifically, ...

A long error occurred while using the payloadaction feature of the Redux Toolkit

import { createSlice, PayloadAction, createAsyncThunk } from "@reduxjs/toolkit" import axios, { AxiosError} from "axios" type user = { id: number, token: string } export type error = { error: string } interface authState { user: user | ...

What is the process of sending a file from a remote URL as a GET response in a Node.js Express application?

Situation: I am working on a Multi-tier Node.js application with Express. The front end is hosted on an Azure website, and the back end data is retrieved from Parse. I have created a GET endpoint and I want the user to be able to download a file. If the f ...

Encountering the error "When calling reset() in Vue JS, getting the error message 'Cannot read property 'map' of undefined' in the following file"

Encountering the following error when attempting to reset, as shown in the screenshot:- > vue.esm.js:1897 TypeError: Cannot read property 'map' of undefined > at c.setResults (store.js:61) > at vuex.esm.js:785 > ...

Deleting an element from an array stored in local storage with the help of jQuery

Summary: Developing a front-end wish list feature Tech Stack: Utilizing HTML5 (localStorage), CSS, and jQuery Key Features: Ability to add and delete items dynamically with real-time count display Challenge: Issue encountered when trying to remove added ...

Utilize javascript/jquery for transforming HTML table data to JSON

Whenever I click the "+" button, my table rows are dynamically generated. After populating the fields and clicking the submit button next to "+", the JSON data is displayed in the console, as shown in the image below. While generating the JSON data, I aim ...

Having multiple Angular two applications running simultaneously within a single webpage

I have encountered an issue while trying to display two separate Calendars on a single page. The first Calendar loads successfully, but the second one does not load at all. There seems to be no attempt made to load it. As I am relatively new to Angular, I ...

Unable to retrieve module from directive template in Angular

I am currently working on creating a wrapper component for ngAudio. This wrapper will act as the player with controls and will interact with ngAudio's functions. However, I am facing some scope issues with it. I can inject ngAudio into the component&a ...

Troubleshooting Angular 2: Instances of Classes Not Being Updated When Retrieving Parameters

I am facing an issue with the following code snippet: testFunction() { let params = <any>{}; if (this.searchTerm) { params.search = this.searchTerm; } // change the URL this.router.navigate(['job-search'], {q ...

Tips for uploading Files and a List of dictionaries with Pydantic's BaseModel in FastAPI

I am struggling with the code provided below: from fastapi import File, UploadFile, Request, FastAPI, Depends from typing import List from fastapi.responses import HTMLResponse from pydantic import BaseModel, Field from typing import Optional app = FastAP ...

Unable to load data from RestAPI into POJO

section, I have integrated android-bootstrap into my project using the resources provided at https://github.com/AndroidBootstrap/android-bootstrap. The project structure remains unchanged, and authentication is not implemented. My application calls a REST ...

Tips for transferring data from a parent component to a child component in React?

Recently, I've been restructuring a small application that was initially confined to one file by breaking it into its own separate components. Right now, I have a child component called UsersTable which I am displaying within the parent component User ...

Update the appearance of a webpage using a custom JavaScript function

My goal is to modify a CSS style whenever a button is clicked. In order to achieve this, I have implemented a JavaScript function that creates a new class for CSS along with several other functionalities. Here's how the JS function currently appears: ...

A thrilling twist on the classic game of Tic Tac Toe, where X and

I am having trouble with switching between the cross and circle symbols in my Tic Tac Toe game. The code seems to be set up correctly, but it's not functioning as expected. Any suggestions on how to fix this? Here is the JavaScript code: varcode va ...