s427
s427

Reputation: 1566

Pinia state loosing reactivity when used in an object?

Trying to wrap my head around reactivity when it comes to states from a Pinia store.

I have the following store (@/stores/settings.js):

import { defineStore } from 'pinia'

export const useSettings = defineStore('Settings', {
  state: () => ({
    useDarkTheme: false
  }),
  persist: true
})

And the following component (App.vue):

<script setup>
import { ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useSettings } from '@/stores/settings'

const settings = useSettings()
const { useDarkTheme } = storeToRefs(settings)

let appClasses = ref({
  'test-class': true,
  'dark-theme': useDarkTheme.value
})
</script>

<template>
  <div class="app-wrapper" :class="appClasses">
    <div class="app-content" :class="useDarkTheme ? 'đark' : 'light'">
            /* ... */
        </div>
  </div>
</template>

On the app-content div, useDarkTheme is reactive: whenever its value changes in the store, the class switches betwenn "light" and "dark". No need to reload the app.

However when used in the appClasses object, useDarkTheme seems to loose its reativity. The "dark-theme" class is applied (or not) based on the value stored in Pinia when the component is loaded, but then it isn't updated to reflect the change that occurs in the store (until the component is loaded again, e.g. by reloading the app). The same is true if I use "reactive" instead of "ref".

What am I missing here?

Upvotes: 0

Views: 477

Answers (2)

moon
moon

Reputation: 1132

Use computed instead of ref.

let appClasses = computed(()=>{
return {
  'test-class': true,
  'dark-theme': useDarkTheme.value
}
})

Upvotes: 1

s427
s427

Reputation: 1566

Turns out I should have used useDarkTheme instead of useDarkTheme.value in my object:

let appClasses = ref({
  'test-class': true,
  'dark-theme': useDarkTheme
})

Thanks to @chiliNUT for the tip!

Upvotes: 1

Related Questions