2

What is the simplest way to initialize data in a Vue component from an async api call in a vuex store. The component mounts before the data is available.

Consider:

export default {
data () {
  return {
    loanAmount: 300000,
    thirtyFixedAPR: null,
    fifteenFixedAPR: null,
    fiveArmAPR: null
  }
},
methods: {
  fetchRates () {
    this.thirtyFixedAPR = this.$store.state.rates.thirtyFixed.apr
    this.fifteenFixedAPR = this.$store.state.rates.fifteenFixed.apr
    this.fiveArmAPR = this.$store.state.rates.fiveArm.apr
  }
},
mounted () {
  this.fetchRates()
}}

I want to call the fetchRates method once after the api call in the vuex store is finished. I'd use a computed property but I only want to initialize the data, not watch it. I've experimented with a few workarounds using watchers that don't seem very elegant and I have a feeling there is a simpler answer to this.

Thanks for your help.

7
  • have you tried doing it in the "created" method instead of mount()? Commented Jan 10, 2018 at 22:24
  • Yes. No combination of lifestyle hooks seems to work. Commented Jan 10, 2018 at 22:35
  • what if you put in a delay, so inside mounted() make the component wait a few seconds before calling vuex for data? Commented Jan 10, 2018 at 22:43
  • That probably is the simplest solution I just tend to stay away from delays as much as possible. Commented Jan 10, 2018 at 22:52
  • Yea I agree. What about having all those properties returned by 1 function and that function returns a promise, then u give the promise a callback and extract your data when network call is complete. Commented Jan 11, 2018 at 1:26

2 Answers 2

1

You need to use subscribe in Vuex.

Basically;

const myMutationListener = this.$store.subscribe((mutation, state) => {
  if (mutation.type === 'MY_MUTATION_INSIDE_VUEX'){
   this.parameter1 = mutation.payload.parameter1
   this.parameter2 = mutation.payload.parameter2
  }
})
Sign up to request clarification or add additional context in comments.

Comments

0

Try to make getter for your vuex store then retrieve your data from it from your page computed.

Store ===> getters

 getters: {
    thirtyFixedAPR: (state) => state.rates.thirtyFixed.apr,
    fifteenFixedAPR : (state) => state.rates.fifteenFixed.apr,
    fiveArmAPR: (state) => state.rates.fiveArm.apr,
}

page.vue

computed: {
    ...mapGetters({
        thirtyFixedAPR: "thirtyFixedAPR",
        fifteenFixedAPR : "fifteenFixedAPR",
        fiveArmAPR: "fiveArmAPR"
    }),
},

Hope this helps you out.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.