MattB
2 months ago
556
2
Vue

How vuex works with Axios

Posted 2 months ago by MattB

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?

Please sign in or create an account to participate in this conversation.