Home > OS >  do you use getters or make http get to retrieve data on mounted? Vue 3 and Vuex
do you use getters or make http get to retrieve data on mounted? Vue 3 and Vuex

Time:10-03

I have any data in list:

<ul> 
  <li v-for="data in allData" :key="data">
    {{ data.name }}
  </li>
</ul>

very simple example but i want to retrieve data from vuex no from component..

mounted() { 
      axios.get("endpoint")
        .then(res => { 
          this.allData = res.data;
        })
        .catch(err => {
          console.log(err);
        }); 
}

This is work but i think i can better to retrieve data from vuex..

I have function in action.js file

  [GET_COMPETITOR_ACTION_DATA](context) { 
    axiosinstance.get('competitors').then(res => {
      console.log('res mu' , res); 
      context.commit(GET_COMPETITOR_MUTATION_DATA, res.data); 
    }).catch(err => console.log(err));
  }

I also have a function in getters.js

[GET_COMPETITOR](state){ 
    return state.competitor;
}

in mutations.js i have:

[GET_COMPETITOR_MUTATION_DATA](state,payload){ 
    payload.map(allD => state.competitor.push(allD)); 
}

Right now in components:

WHen try

  computed: {
    ...mapGetters("competitor", {
      competitor: GET_COMPETITOR
    })

and use:

<ul> 
  <li v-for="data in competitor" :key="data">
    {{ data.name }}
  </li>
</ul>

no work.

when try:

...mapActions("competitor", {
  allDataCompetitorData: GET_COMPETITOR_ACTION_DATA
}),

<ul> 
  <li v-for="data in allDataCompetitorData" :key="data">
    {{ data.name }}
  </li>
</ul>

Also no work..

My question ->

How best to retrieve data from the store for this get load on the mounted or created?

And

Why don't my attempts work?

CodePudding user response:

Try to wait for response :

async mounted() { 
  await this.allDataCompetitorData()
}

then in template use getter:

<ul> 
  <li v-for="data in competitor" :key="data">
    {{ data.name }}
  </li>
</ul>
  • Related