The watch function was triggered for a different key in the array from the one that

What is the best way to limit the watch function to only trigger for the selected key in the data array?


import { useSessionStorage } from "@vueuse/core";

const defaultState = {
  data: [
    { key: 1, name: "A" },
    { key: 2, name: "D" },
    { key: 3, name: "C" },
  ]
}

const state = useSessionStorage("settings", defaultState, {
  mergeDefaults: true,
});

const key0Name = toRef(
  () => state.value.data[0].name
);
watch(key0Name, (newOpts) => {
  console.log("key0Name", newOpts);
});

state.value.data[0].name = "Z" // Triggers watch function.
state.value.data[1].name = "Z" // Also triggers watch function.

Answer №1

Looks like I need to utilize toRefs with the array of objects.

const info = toRefs(state.data.data);

watch(info[0], ...)

If I want to watch the name:

const nameInfo = toRef(info.name)

watch(nameInfo, ...)

Seems like the state is a ref but the properties are regular JS objects. Therefore, using toRefs and toRef are necessary to establish a two-way data bind with those properties. You can easily pass the state variables directly to child components and observe their changes using these refs.

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

Encountering a ReferenceError message that says "readFile is not defined

Currently, I am in the process of learning Node.js and encountering an issue. When I type 'node .' in the terminal, I receive a ReferenceError: readFile is not defined message. Below is the code snippet: const express = require("express"); co ...

What causes a significant influx of packages each time I execute the command `npm install`?

https://i.sstatic.net/a3BxV.png https://i.sstatic.net/dcVXS.png Could this be related to my overall package.json file? ...

Resolving Cross-Origin Resource Sharing issues with AWS SDK (Lightsail API) and Vue.js

I'm currently working on a small vue.js application that utilizes aws-sdk to retrieve information about Lightsail instances. However, I keep encountering this issue. :8081/#/:1 Access to XMLHttpRequest at 'https://lightsail.us-west-2.amazonaws.c ...

Retrieve items within an array of objects in MongoDB using an array of IDs (using the $in operator in aggregation)

In my MongoDB database, I have a collection of stores [ { "_id" : ObjectId("6043adb043707c034d5363b7"), "shopId" : "shopid1", "appId" : "777", "shopItems" : [ { ...

Dynamic horizontal scrolling

I need help implementing a site using React that scrolls horizontally. I'm unsure how to implement certain aspects, so I am looking for some assistance. Within a wrapper, I have multiple container Divs. <div class="wrapper"> <div class=" ...

I am having trouble with searching for places using the Google API in my Node

Recently, I've been working on integrating the Google Maps API places feature into my project. Thankfully, I came across an npm module that simplifies the process of connecting it to node. Check out the npm module here! After downloading the module ...

Galaxy S5 browsers experiencing issues with website responsiveness

I've been using jquery to dynamically remove a div in order to change the appearance of my home screen on smaller devices. It's been successful on my Macbook Air and Iphone X, but unfortunately, it doesn't seem to work properly on Android de ...

Implementing code to scroll and play multiple videos simultaneously using JavaScript and jQuery

This solution currently only works for one video, but it needs to be able to handle multiple videos (TWO OR MORE) <html> <head> <script src="https://code.jquery.com/jquery-1.8.0.min.js" integrity="sha256-jFdOCgY5bfpwZLi ...

Adding a JavaScript script tag within a React app's ComponentDidMount - a guide

I am currently in the process of implementing Google Optimize on my website. I need to include the following script tag within my page: <script>(function(a,s,y,n,c,h,i,d,e){s.className+=' '+y;h.start=1*new Date; h.end=i=function(){s.classN ...

Rendering faces with a different texture using BufferGeometry in Three.js

Here is my output date: geom[0] = { texturesindexT: new Int16Array([0,1,2,3]), texturesindexS: new Int16Array([-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,...]), materialsindexT: new Int16Array([-1,-1,-1,-1]), materialsindexS: new Int16Array([-1,0,1,2,3,4,5,0,6,2,7,8 ...

Modifying text dynamically in AngularJS by cycling through an array of strings

Is it possible to create a text carousel in my angular controller without using an infinite loop? For example: //html <span> {{ notes }}</span> //angular controller var i = 0; var array = ["A", "B", "C", "D", "E"]; while (true ...

Applying the jqtransform plugin to all forms except for one

We've implemented the jQuery jqtransform plugin to enhance the appearance of our website's forms. However, there is one particular form that we'd like to exclude from this transformation. I made adjustments to the script that applies jqtrans ...

Next.js presents a challenge with double-language applications

I am currently in the process of developing a web application using Next.js that will cater to users who speak my native language and English. I have a specific approach in mind: First, I plan to create a folder: /pages/en-us pages/ |--(all app pages) |- ...

Challenges compiling 'vue-loader' in Webpack caused by '@vue/compiler-sfc' issues

The Challenge Embarking on the development of a new application, we decided to implement a GULP and Webpack pipeline for compiling SCSS, Vue 3, and Typescript files. However, my recent endeavors have been consumed by a perplexing dilemma. Every time I add ...

Determining the page's coordinates in ColdFusion

Whenever I use iframes or frames on older websites, I implement an additional security measure using a JavaScript function: <SCRIPT LANGUAGE="JavaScript1.1"> if (top == self) self.location.href = "../index.cfm"; </SCRIPT> I also include an ...

Converting Database Information to JSON Format for Mobile Authentication Form

Currently, I am working on a Mobile App project using Phonegap that requires users to log in before retrieving JSON data. This PHP page is responsible for connecting to the mobile site and fetching the necessary information. <?php $con = mysqli_connec ...

If the user fails to respond, Alexa will show an error message indicating that the skill response was marked as a failure

After completing the code for my Alexa skill, I encountered a problem. My fact-based skill template is set to wait for responses after the output, but if Alexa doesn't hear a response within 8 seconds, it generates an error (Skill response was marked ...

Utilizing VueJS for Seamless Integration with External Web API Token Management Systems

As I work on my VueJS SPA project, one of the key components involves interacting with a 3rd Party Web API. In order to obtain a token from this API, I will need to pass credentials that are provided by the third party. I am considering whether it is bes ...

Is there a way to verify the existence of a user in mongoose?

Currently, I am attempting to verify the existence of a user with the code below: const userExist = await User.find({ username: req.body.username }); if (userExist) return res.status(400).send({ message: "User already exists" }); However, eve ...

Updating and showing a variable in a PHP file using JavaScript within an HTML webpage

My goal is to establish a variable in a PHP file on my server named "likes." Subsequently, I wish to incorporate a like button on my HTML webpage that, when clicked, will utilize JavaScript to modify the "likes" variable in the PHP file and increase it by ...