Home > front end >  How to catch returned value from mutation in another mutation Vuex
How to catch returned value from mutation in another mutation Vuex

Time:12-18

I am trying to access to a getter from an action but it is giving an error that: getters.isCardLiked is not a function

store/index.js

export const getters = {

  isCardLiked(state, id) {
    const found = state.likedCards.find(likedCard => likedCard.id === id)
    console.log('found', found); // object
    return found
  },
  
 },
 
export const actions = {

  likedCardsHandler({ dispatch, commit, getters }, id) {
    console.log('here', getters.isCardLiked(id));
  },
 }

CodePudding user response:

likedCardsHandler is an action or a mutation?
If it's an action, you can find it in the action context and use it from there.

With something like this

actions: {
  likedCardsHandler ({ getters }) {
    console.log('here', getters.isCardLiked)
  }
}

Otherwise, I guess you could try const card = isCardLiked.

this is not defined in the store itself since it's a .js file.

CodePudding user response:

export const getters = {

  isCardLiked: (state) => (id) => {
    const found = state.likedCards.find(likedCard => likedCard.id === id)
    console.log('found', found); // object
    return found
  },
 }
 
 export const actions = {
 likedCardsHandler({ dispatch, commit, getters }, id) {
    console.log('here', getters.isCardLiked(id));
   }
  },
 }

Especially thank to @kissu

CodePudding user response:

You could use computed method with filter for returning found object like this. So I am guessing there is a like button such as this. Store page

import createStore from 'vuex';
const store=createStore({

state:{
cards:{
  A:{
   id:1.
   likes:0
 }, 
 B:{
 id:2,
 likes:0
 }
}
}
actions:{
   changeCards({commit}, payload){
   commit('changeCard',payload)
 }
}
mutations:{
  changeCard(state,payload){
  if(state.cards.id==payload)
  state.cards.likes  ;
}
}

})
export default store;

Now in the App.js

  <ul>
  <li v-for="card in cards">
  <button @click="likeButtonClicked(card.id)">Like</button>
  </li>
  </ul>
   <li v-for="likedCard in likedCards">{{likedCard}}
     </li>
 <ul>
<li></li>
</ul>

 methods:{
  likeButtonClicked(id){
   this.$store.dispatch('changeCards',id);
 }
}



computed:{
  cards(){

  return this.$store.state.cards;
}
likedCards(){
  return cards.filter(card=>card.id.includes(this.$store.state.cards.likes>0))
}

I hope you are getting the point of all this. I hope this helps

  • Related