Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Watch handler was called unexpected in vue2 with pinia #1369

Open
reuwi opened this issue Jun 13, 2022 · 1 comment
Open

Watch handler was called unexpected in vue2 with pinia #1369

reuwi opened this issue Jun 13, 2022 · 1 comment
Labels
bug Something isn't working has workaround The issue contains a temporary solution to get around the problem vue 2.x Specific to Vue 2 usage

Comments

@reuwi
Copy link

reuwi commented Jun 13, 2022

Reproduction

https://github.com/reuwi/pinia-vue2-watch-bug-repro/tree/master

Steps to reproduce the bug

Step1: Clone this repo to local

git clone [email protected]:reuwi/pinia-vue2-watch-bug-repro.git

Step2: install dependencies

npm install && npm run serve

Step3: open http://localhost:8081/ in browser

Expected behavior

No alert is promoted

Actual behavior

Got an promoted alert with 'lol changed'

Additional information

After some debugging, I guess that the problem may came from initWatch when collect dependencies. When excute get function to add dep, pinia will travers the state object, which cause wrong dependency relation.

image

@posva
Copy link
Member

posva commented Jun 15, 2022

Have you tried this in Vue 3? It could be a bug with effectScope and Vue 2.

As a workaround, you can use mapStores() instead and watch the store or you can ensure the store is instantiated before this.foo is called. This can be achieved by using mapStores() and reading any property from the store before creating the watcher:

export default {
  name: 'App',
  data: () => ({
    color: '#f00',
    swatches: ['#f00', '#ccff00', '#eee', '#0f0'],
  }),
  computed: {
    ...mapState(useStore, ['lol', 'bar']),
    ...mapStores(useStore),
  },
  methods: {
    ...mapActions(useStore, ['setBar']),
  },
  created() {
    this.fooStore.$state // store is instantiated
    this.$watch(
      'lol',
      () => {
        console.log('lol changed')
      },
      { deep: true }
    )
    this.setBar()
  },
}

@posva posva added bug Something isn't working has workaround The issue contains a temporary solution to get around the problem vue 2.x Specific to Vue 2 usage labels Jun 15, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working has workaround The issue contains a temporary solution to get around the problem vue 2.x Specific to Vue 2 usage
Projects
Status: Vue 2
Development

No branches or pull requests

2 participants