Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vincent15000's avatar

Watching for a modification in a pinia store

Hello,

I have this code.

const authStore = useAuthStore()

let isAuthenticated = ref(authStore.isAuthenticated)

watch(
  () => authStore.isAuthenticated,
  () => {
    isAuthenticated = authStore.isAuthenticated
  },
)

....

<router-link to="/login" v-if="!isAuthenticated.value">
	<v-btn icon="fa:fas fa-right-to-bracket" color="white"></v-btn>
</router-link>

<v-btn @click="logout" icon="fa:fas fa-right-from-bracket" color="white" v-if="isAuthenticated.value"></v-btn>

// OR

<router-link to="/login" v-if="!authStore.isAuthenticated">
	<v-btn icon="fa:fas fa-right-to-bracket" color="white"></v-btn>
</router-link>

<v-btn @click="logout" icon="fa:fas fa-right-from-bracket" color="white" v-if="authStore.isAuthenticated"></v-btn>

And I'm quite sure that the watch is not useful. However no one works. For example with both codes the icon doesn't change.

What am I doing wrong ?

Can you help me with some suggestions ?

Thanks a lot.

V

0 likes
4 replies
ChrisSimons's avatar
Level 1

Is the ‘isAuthenticated’ a getter in the pinia store? #2 is 100% the way to go here and should work on if it’s a getter method.

1 like
vincent15000's avatar

@ChrisSimons It's effectively a getter.

Way 2 doesn't work.

So I should perhaps check if the store is really updated or not.

ChrisSimons's avatar

@vincent15000 direct 2-way binding doesn't work on stores, no although I didn't see anywhere in your original example that required it.

Anyways, when using stores you should always use getters to read from the store's state and actions to modify the store's state.

export const useAuthStore = defineStore("auth", {
  state: () => ({
    authenticated: false
  }),
  getters: {
    isAuthenticated: (state) => state.authenticated
  },
  actions: {
    setIsAuthenticated (value) {
      this.authenticated = value
    }
  }
});

You can implement 2-way binding using using the modelValue prop and update:modelValue emit event (which is how v-model works under the hood).

<input 
    :modelValue="useAuthStore().theGetter"  // e.g. isAuthenticated
    @update:modelValue="useAuthStore().theSetterAction(value)" // e.g. setIsAuthenticated
  />

When testing my side, I can see that the getter is reactive:

watch(
  () => useAuthStore.isAuthenticated,
  () => console.log('changed') // fires when the value returned from isAuthenticated changes
)
1 like

Please or to participate in this conversation.