Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue mapState non reactive

I try to get the state from the store using the mapState function, But I can't use the generated code that returns the values into my template code ...

<template>
         // Some code
                <template v-if="!isLoggedIn">
                    // Some code
                </template>
                <template v-else>
                    // Some code
                    {{ currentUser.name }} 
                </template>
    
        // Some code
</template>

<script>
    import { mapState } from "vuex";

    export default {
        // Some code
        computed: {
          ...mapState({auth : ['currentUser', 'isLoggedIn','customers']})
        }
    }
</script>

instead the following code work

<script>
    import { mapState } from "vuex";

    export default {
        // Some code
        computed: {
          currentUser() {
                return this.$store.state.auth.currentUser
            },
            isLoggedIn() {
                return this.$store.state.auth.isLoggedIn
            },
        }
    }
</script>

Warning message

[Vue warn]: Property or method "isLoggedIn" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

Thanks in advance

like image 770
hassen zouari Avatar asked Apr 29 '26 23:04

hassen zouari


1 Answers

The right syntax to access non-root properties is the following (using arrow functions) :

computed: {
...mapState({
  currentUser: state => state.auth.currentUser,
  isLoggedIn: state => state.auth.isLoggedIn,
  customers: state => state.auth.customers
})}

Check the documentation.

like image 136
Gonzoarte Avatar answered May 02 '26 12:05

Gonzoarte