Mark
Mark

Reputation: 169

Vuex not returning expected state

I have a pop up modal that should appear if the user has no transactions. depositHistory is an array with these transactions. If its length is greater than 0, the pop up should remain hidden. If its length is equal to 0, the pop up should render.

The user account I'm using has 2 transactions. The pop up shouldn't show but it does. The console.log() returns an empty array which is not correct. I have another component someone else wrote which uses depositHistory in the same way and is working as expected.

Component:

<template>
  <div v-if='renderModal'>
    <p>Fund your account</p>
  </div>
</template>

<script>
const DepositGetter = namespace("deposit").Getter

const AppProps = Vue.extend({
data: () => {
  return {
    renderModal: false
  }
},
beforeMount() {
  // renders modal if user has no transactions
  if (this.depositHistory.length === 0) this.renderModal = true

  console.log(JSON.parse(JSON.stringify(this.depositHistory)))
  // usually returns [__ob__: Observer]
  // added JSON methods so now it logs []
}

export default class HomeGameBanner extends AppProps {
  @DepositGetter depositHistory
}
</script>

I don't think you need this but just in case.

Store:

type DepositGetter = GetterTree<DepositState, RootState>;

export const getters: DepositGetter = {
  depositHistory: state => state.content
};

export const deposit: Module<DepositState, RootState> = {
  getters
}

Upvotes: 0

Views: 42

Answers (1)

KaranV
KaranV

Reputation: 312

the data object is initialized after beforeMount so try and execute in mounted like this

<template>
  <div v-if='renderModal'>
    <p>Fund your account</p>
  </div>
</template>

<script>
const DepositGetter = namespace("deposit").Getter

const AppProps = Vue.extend({
data: () => {
  return {
    renderModal: false
  }
},
mounted() {
this.$nextTick(function () {
  // renders modal if user has no transactions
  if (this.depositHistory.length === 0) this.renderModal = true

  console.log(JSON.parse(JSON.stringify(this.depositHistory)))
  // usually returns [__ob__: Observer]
  // added JSON methods so now it logs []
})
}

export default class HomeGameBanner extends AppProps {
  @DepositGetter depositHistory
}
</script>

Fore reference

enter image description here

Upvotes: 1

Related Questions