Pinia subscribe and recursivity : manipulating states

pinia subscribe method is very powerful, in any component you can subscribe to global state variables, manipulate them and use this combination as communication between components. It's also a dangerous game, as infinite recursivity can occur.

counting reactivity occurences

first thing is to measure the number of recursive calls to your subscribe

var recursiveIndex=0
onMounted(() => {
  waveAppStore.$subscribe((mutation, state) => {


Modifying state variable within the subscribe

Then, when you need to work on state variables, one solution is to the state before altering it globally. Be careful to copy a value, not a reference other wise you will manipulate the state itself as by default, javascript copies arrays by reference (this is called shallow copy as opposed to deep copy).

const copy = JSON.parse(JSON.stringify(state));

To top