vue.jsvuexvuejs3vuex4

How to use result of api with actions from Vuex


I'm trying to retrieve user favorites by axios when user is loggedIn. For that I use Vuejs with Vuex. All about logging process is ok, but about favorites, I'm missing something but I don't know what.

My store.ts is like this :

export const store = createStore({
    state: {
        user: null,
        token: null,
        favorites: []
    },

    mutations: {
        setUser(state, user) {
            state.user = user;
        },
        setToken(state, token) {
            state.token = token;
        },
        setFavs(state, favorites) {
            state.favorites = favorites;
        },
    },
    actions: {
        getFavorites({ commit }) {
            axios
                .post("URL_HERE", {
                    userId: this.state.user,
                })
                .then((res) => {
                    //console.log(res);
                    commit('setFavs', res.data)

                })
                .catch((error) => {
                    console.log(error);
                })
        }
    },
    getters: {
        getFavs: (state) => state.favorites
    },
});

On my Favorites component I have :

export default defineComponent({
  name: "Favorites",
  data() {
    return {
      favorites: null,
    };
  },
  computed: {
    ...mapGetters(["isLoggedIn"]),
    ...mapGetters({ Favorites: "getFavs" }),
  },
});

Then in template :

<div v-for="favorite in Favorites" :key="favorite.event_id">
 <li>{{ favorite }}</li>
</div>

Solution

  • You need to dispatch the action in the mounted hook:

    export default defineComponent({
      name: "Favorites",
      data() {
        return {
          favorites: null,
        };
      },
      computed: {
        ...mapGetters(["isLoggedIn"]),
        ...mapGetters({ Favorites: "getFavs" }),
      },
     methods:{
      ...mapActions(['getFavorites'])//map the actions as you did with getters
     },
     mounted(){
      this.getFavorites();//dispatch the action
    },
    //or use a watcher
    watch:{
    isLoggedIn(newVal,oldVal){
      if(newVal){
            this.getFavorites()
       }
    }
    
    }
    });