Home  >  Q&A  >  body text

Observing state object in pinia does not trigger when object changes

<p>I have a deep object in my pinia state where I want to place an observer. </p> <pre class="brush:js;toolbar:false;">export const useProductStore = defineStore("product", { state: () => ({ attributes: {}, }), }); </pre> <p>When an object has data inside it, it looks like this: </p> <pre class="brush:json;toolbar:false;">attributes: { english: { 0: { key: "key1", value: "value1" }, 1: { key: "key2", value: "value2" }, ... } } </pre> <p>I'm trying to place an observer on this object, but when the value changes, the observer doesn't fire. This is the component I'm trying to do this in: </p> <pre class="brush:js;toolbar:false;"><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> </pre> <p>This comes directly from the pinia documentation, but when I change the state, nothing happens. Using vue dev tools I can see the state object is changing so I know it's reactive. What did I miss? </p>
P粉002546490P粉002546490417 days ago533

reply all(1)I'll reply

  • P粉668113768

    P粉6681137682023-08-29 09:47:17

    storeToRefs Generate ref()s.

    You say this example "comes directly from the pinia documentation", but I doubt you found ref propagated anywhere in the pinia documentation. If you do this, then this is a bug and should be pointed out to posva by raising an issue on pinia's repository.

    You can watch it directly for reference:

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

    ...or you can use an arrow function to view its .value1:

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

    Note that the newVal and oldVal parameters are Agent 2. To access its target, use toRaw.

    Working Demonstration. p>


    1 - It allows for narrower observers, for example:

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

    2 - If you put an object into ref() " the object is related to reactive( )" Perform deep reactions (see Details). Also readReactive Proxy vs. Raw Proxy .

    reply
    0
  • Cancelreply