Search code examples
javascriptvue.jsvuejs2axiosvuex

Vuex not updating state when using actions


Trying to get my head around VueX but struggling to get Axios to work with it. I have the following in my store.js file:

 state: {
    cards: [],
    currentPage: 1,
    lastPage: 2,
  },
  actions: {
    loadGradients(pageNumber) {
      if (axios == null) {
        return;
      }
      axios
        .get("/api/gradients?page=" + pageNumber + "&sort=" + "created_at")
        .then((res) => {
          if (res.status === 200) {
            state.cards = res.data.gradients.data;
            state.lastPage = res.data.gradients.last_page;
            state.currentPage = res.data.gradients.current_page;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },

I'm calling it through the following function in my main app.js file:

  created() {
    this.loadGradients(1);
  },
  methods: {
    loadGradients: function (pageNumber) {
      this.$store.dispatch("loadGradients");
    },
  },

But when I run the page, the array in the store.js file isn't being updated it seems, even though the data is being returned correctly from the database. Not sure what I did wrong? If I have to use a combination of actions and mutation, how would I go about that please?


Solution

  • Can you try assigning the response data to the store using mutations

    mutations = {
      setCards:(state,data) => state.cards = data,
      setCurrentPage:(state,value) => state.currentPage = value,
      setLastPage:(state,value) => state.lastPage = value
    }
    

    And inside actions

            loadGradients({commit},pageNumber) {
                if (axios == null) {
                    return;
                }
                axios
                    .get('/api/gradients?page=' + pageNumber +'&sort=' + 'created_at')
                    .then(res => {
                        if (res.status === 200) {
                           // calling the mutations
                            commit('setCards',res.data.gradients.data);
                            commit('setCurrentPage',res.data.gradients.current_page);
                            commit('setLastPage',res.data.gradients.last_page);
                        }
                    })
                    .catch(err => {
                        console.log(err);
                    });
            },