davestewart/vue-class-store

Setting property in the constructor does not trigger watch

Opened this issue · 3 comments

This might be well-intentioned, but we just stumbled upon the fact that watches are only triggered after the class has been initialized (so not in the constructor).

The detailed explanation in the readme seems even suggests that. People might expect this to work though, so maybe it makes sense to add a more prominent note somewhere?

Hey Martin,

Glad you're using it!

EDIT: just reread your ticket and actually I misunderstood the intention of your bringing this up.

The detailed explanation in the readme seems even suggests that. People might expect this to work though, so maybe it makes sense to add a more prominent note somewhere?

Where and what would you suggest to clarify? Feel free to PR the readme.


I'll take a look into this. In the meantime, you could also just call the watch function in the constructor, of course:

constructor () {
  this.doThing()
}

For Vue 2, because it's literally a straight re-build to a new Vue() you could try (I haven't checked this yet):

'on:thing' = {
  immediate: true,
  handler: 'doThing'
}

For Vue 3, I think I would need to look to see how this could be done. I see that watchEffect is designed to watch but also trigger an immediate firing of the watch function.

Do you want to try and get back to me?

Just tried the immediate option I suggested above, and it does indeed work:

image

https://codesandbox.io/s/tender-firefly-3ksqy?file=/store/Rectangle.ts

I'm kind of stretched at the moment, but I'll leave this ticket open though, and will look into it again.

Not 100% sure if the watch should be triggered in the constructor or not. It wasn't intended like that, but having the option to call it manually is actually a nice side effect.

Another option might be a syntax change, so perhaps something like this:

'on:thing!' (value: number) { ... }

Anyway, let me know your thoughts :)

Well, thanks for your help and for your work on this! Having started using this library in our project not long ago, I really like it so far. I used vuex before. I hope using vue-class-store as a store layer works out well in the end. This is so much more sane to use.

For the workaround, well, we are using Vue3 in this project, so we cannot use it. I will propose a change to the readme if we don't find a good solution here. Btw, I really like your on:thing! syntax proposal 👍