Dima Kovbasa
Dima Kovbasa

Reputation: 87

Can't update data based on props

I have a components hierarchy, A, B, and AccountCard. In component A, I executed an account validation, and pass the result to component B in props, and that component based on props should update data and pass it to the child component AccountCard. If I use the bellow approach I get the error "Cannot read property 'isActiveAccount' of undefined". Based on this variable, I must show one or another button. How I can update data based on props?

{
.....
<template>
    <AccountCard
      v-for="(item, index) in accountDetails"
      :key="index"
      :item="item"
    />
</template>
export default {
  components: {
    .....
  },
  props: {
    isActiveAccount: {
      type: Boolean,
      default: false
    }
  },
  data: () => ({
    ......
    accountDetails: [
      {
        isActive: this.isActiveAccount,
      }
    ]
  })
}

Upvotes: 0

Views: 613

Answers (1)

Amaarockz
Amaarockz

Reputation: 4684

When the props changes and if you want to update the data value then use the below approach

export default {
  components: {
    .....
  },
  props: {
    isActiveAccount: {
      type: Boolean,
      default: false
    }
  },
  data: () => ({
    ......
    accountDetails: {
        isActive: false, // set inital value to be null if you want to check if the watch handler is really working
      }
  }),
 watch: {
    isActiveAccount(newVal) {
     this.accountDetails.isActive = newVal; //Change added
 },
}

Changes: Instead of having it as an array I suggest you to keep it as an object. Moreover watch will get triggered as soon as the mounted is done, so you need not worry

Upvotes: 1

Related Questions