Observing the state object in Pinia does not trigger when the object undergoes changes

I am facing an issue with setting a watcher on a deeply nested object in my Pinia state.

export const useProductStore = defineStore("product", {
  state: () => ({
    attributes: {},
  }),
});

When the object has data inside it, it looks something like this:

attributes: {
  english: {
    0: {
      key: "key1",
      value: "value1"
    },
    1: {
      key: "key2",
      value: "value2"
    },
    ...
  }
}

I have tried to set a watcher on this object, but unfortunately, the watch does not trigger. Here is the component where I am attempting to do this:

<script setup>
  import { useProductStore } from "@/stores/ProductStore";
  import { storeToRefs } from "pinia";

  const productStore = useProductStore();
  const { attributes } = storeToRefs(productStore);

  watch(() => ({...attributes}), (newValue, oldValue) => {
    console.log(oldValue);
    console.log(newValue);
  }, { deep: true });
</script>

Although this code is directly from the Pinia documentation, I am not seeing any changes reflected when the state is updated. The Vue dev tools show that the state is indeed updating reactively. Can anyone help me figure out what I am missing?

Answer №1

storeToRefs generates ref()s.

The example you mentioned as coming from the Pinia documentation seems unlikely since there is no mention of spreading a ref in the official Pinia docs. If this was an error, it should be brought to Posva's attention by opening an issue on the pinia repository.

A ref can be directly watched like this:

watch(
  attributes,
  handler, 
  { deep: true }
)

...or you could watch its .value using an arrow function for finer control:

watch(
  () => attributes.value,
  handler,
  { deep: true }
)

Keep in mind that the newVal and oldVal arguments are actually Proxies. To access their underlying targets, use the toRaw function.

Here is a working demo for reference.


1 - This method allows for more focused watchers, like so:

watch(
  () => attributes.value[0]?.value),
  handler
)

2 - When placing an object in a ref(), "the object becomes deeply reactive with reactive()" (refer to details). Additionally, check out Reactive Proxy vs Original.

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

Create a duplicate of the prop object by transferring it to a fresh data

Structure of Vue components; UserList.Vue (parent component) UserEditor.vue (child component) A table displaying users is present, when a user is selected, the selectedUser property is updated with the chosen user (within UserList.vue); selectedUser: ...

Please provide the date using the Foundation Datepicker tool

Beginner in JavaScript here! I am having an issue with submitting dates selected using the Foundation Datepicker from . I have searched for solutions on StackOverflow like Post form on select with JQuery Datepick, but none seem to work in my case. If a Ja ...

Having trouble getting the `transformItems` feature in React InstantSearch RefinementList to

I recently integrated the React InstantSearch library into my app and I'm working on customizing the refinement list to display only relevant filters for the active user. I attempted the following code: <RefinementList attributeName="organization" ...

What is the best way to activate a click event in Vue.js?

Hey there! I'm facing a situation where I have a button within the child component that emits an event when clicked. Is there a way to trigger this event when the parent component is mounted? Alternatively, is there another method to achieve this goal ...

Show off markdown formatting without the need for v-html

I run a unique type of platform that allows users to publish their own blog posts using a WYSIWYG editor, and then share them on the site. My top priority is to ensure security against XSS attacks, which is why I am looking for alternatives to using v-htm ...

What steps need to be taken to set up Node.js to accommodate requests from external sources beyond just localhost?

After creating an application using NextJs, I successfully built it and ran it on a node server by executing 'npm run start' in Powershell. Everything works perfectly when accessing it locally through port 80. However, my Windows Server 2019 does ...

Reduce the noise from different versions by utilizing package-lock.json

There may not be a clear-cut answer, but I'm curious to hear how others handle the issue of package-lock.json causing problems when committing to their node repository. Many opinions lean towards committing package-lock.json - ensuring consistent dep ...

Iterating through and dispatching to the modal窶ヲ

Can someone help me figure out why I am encountering a problem where clicking on the button below results in seeing three different objects before being told that invoice is undefined? <tr :key="invoice" v-for="(invoice, index) in invoices"> & ...

Vue fails to trigger a rerender of the list, even when the set function is utilized

I created a list where each item can be removed, and this is how my code looked: Snippet <template v-for="(timeFrame, index) in form.timeFrames"> <el-form-item > ...

Trouble keeping HTML/Javascript/CSS Collapsible Menu closed after refreshing the page

My issue is that the collapsible menu I have created does not remain closed when the page is refreshed. Upon reloading the page, the collapsible menu is always fully expanded, even if it was collapsed before the refresh. This creates a problem as there is ...

What should be transmitted to the front-end following the successful validation of a token on the server?

My process starts with a login page and then moves to the profile page. When it comes to handling the token on the backend, I use the following code: app.use(verifyToken); function verifyToken(req, res, next) { if (req.path === '/auth/google&ap ...

Prevent ESLint from linting files with non-standard extensions

My .estintrc.yaml: parser: "@typescript-eslint/parser" parserOptions: sourceType: module project: tsconfig.json tsconfigRootDir: ./ env: es6: true browser: true node: true mocha: true plugins: - "@typescript-eslint" D ...

Can object-fit be preserved while applying a CSS transform?

Currently, I am developing a component that involves transitioning an image from a specific starting position and scale to an end position and scale in order to fill the screen. This transition is achieved through a CSS transform animation on translate and ...

Tips for transferring form data between pages using ReactJS?

Custom Checkout Implementation This section pertains to the custom checkout implementation utilizing Javascript. The goal is to extract form fields from the CheckoutForm page and utilize them within this checkout.js file for database submission. This pre ...

Unlock the potential of AngularJS services with this innovative design strategy

I am currently developing an AngularJS client application that will communicate with a REST server. To handle the interaction between the client and server, I have decided to use the $resource abstraction from AngularJS. Each resource is being written as ...

Utilizing Typescript for parsing large JSON files

I have encountered an issue while trying to parse/process a large 25 MB JSON file using Typescript. It seems that the code I have written is taking too long (and sometimes even timing out). I am not sure why this is happening or if there is a more efficien ...

When the page is refreshed, the ID passed through params disappears

One of the challenges I am facing involves a component called Subscribers that receives props through params from another component known as Details. These props are used to make an API call and retrieve a list of subscribers, which functions correctly. H ...

Verify if the date string includes the day

Here's the scenario: a user clicks on one of two links, either 2012/10, or 2012/10/15. I am extracting the day value from the link to pass it onto an AJAX request that will change days on an archive page. Is using a regular expression like /\d{ ...

Retrieve HTML content from a JSON object and render it on a web page

I am facing a challenge with decoding html that is in json format. I'm struggling to figure out how to retrieve my html and display it on a page. It seems like json_decode isn't the solution. Can anyone help me with this issue? Appreciate any as ...

What methods can I use to gauge the performance of my angular website?

After completing my web project with nodejs and expressjs on the backend and angularjs on the frontend, I am worried about the performance implications. People say that JavaScript can be dangerous if not used correctly, so I ran jshint to verify my synta ...