mikasa
mikasa

Reputation: 145

Vue Pinia: Toggle function toggles just once and not back

I got a Pinia useStore, where I got a boolean variable and a toggle function:

export const useStore = defineStore('storeID', {
    state: () => ({
        eineVariable: true
    }),
    getters: {
        getEineVariable(state) {
            return state.eineVariable
        }
    },
    actions: {
        toggleFunktion() {
            this.eineVariable = !this.eineVariable
            console.log(this.eineVariable)
        }
    }
})

If I create this div with the clickevent to toggle the color of the div, it just loggs me one toggle from true to false, but not further.

import {useStore} from "../store/index.js"

const store = useStore()

const isActive = computed(() => {
  return store.getEineVariable
})

const toggleBox = computed(() => {
  return store.toggleFunktion()
})

<div class="piniaBox" :class="{ 'active': isActive}" @click="toggleBox"></div>

I really don't see my mistake. Could you guys please help?

Upvotes: 0

Views: 536

Answers (1)

Estus Flask
Estus Flask

Reputation: 222309

A computed is supposed to return a value, it's a mistake to do side effects inside of it.

Should be:

const toggleBox = () => {
  store.toggleFunktion()
}

Upvotes: 3

Related Questions