Implementing pagination parameters in an axios instance within a Vue application

My Store has the following structure:

    const getDefaultState = () => {
        return {
            resources: Object,
            loading: false,
            query: {
                title: null,
                page: 1
            },
            checked: {
                type: Array,
                required: false
            },
            resource: null
        };
    };

    export default {
        namespaced: true,
        state: getDefaultState(),

        getters: {
            resources(state) {
                return state.resources;
            }
        },

        mutations: {
            RESET_STATE(state) {
                Object.assign(state, getDefaultState());
            },
            SET_RESOURCES(state, resources) {
                state.resources = resources;
            },
            SET_QUERY(state, query) {
                state.query = query;
            },
            CHECK_RESOURCE(state, resource) {
                if (state.checked.includes(resource)) {
                    state.checked = state.checked
                        .slice(0, resource)
                        .concat(state.checked.slice(i + 1, state.checked.length));
                } else {
                    state.checked.push(resource);
                }
            },
            FETCH_START(state) {
                state.loading = true;
            },
            FETCH_END(state) {
                state.loading = false;
            }
        },
        actions: {
            resetState({ commit }) {
                commit("RESET_STATE");
            },

            fetchResources({ commit }) {
                commit("FETCH_START");
                debugger;
                axios
                    .get(route("sell_orders.index"), { params: this.state.query })
                    .then(response => {
                        return commit("SET_RESOURCES", response.data);
                    })
                    .catch(error => {
                        throw new Error(error);
                    })
                    .finally(() => commit("FETCH_END"));
            },

            checkResource({ commit }, resource) {
                commit("CHECK_RESOURCE", resource);
            },

            setQuery({ commit }, query) {
                commit("SET_QUERY", query);
            }
        }
    };

In my Vue page:

<template>
    <div class="w-full">
        <div class="card-header">
            <span>{{ __("validation.attributes.sell_order_id") }}</span>
        </div>
        <div class="card-body">
            <sell-order-search
                :query="this.$store.state.sellOrder.query"
                @search="this.search"
                @reset="this.reset"
            ></sell-order-search>

            <scale-loader 
            v-if="this.$store.state.sellOrder.loading" 
            :loading="true"
            ></scale-loader>

            <div v-else>
                <sell-order-table
                    :resources="this.$store.state.sellOrder.resources"
                    @select="checkResource"
                    v-slot="slotProps"
                >
                    <template class="flex justify-between">
                        <router-link
                            class="btn-blue"
                            :to="{ name: 'sellOrderEdit', params: { 
                                id: slotProps.resource.id 
                                } }"
                            v-if="Auth.can('UpdateSellOrder')"
                        >
                            <font-awesome-icon icon="pen" class="align-middle">
                            </font-awesome-icon>
                            <span>{{ __("words.edit") }}</span>
                        </router-link>

                        <router-link
                            class="btn-red"
                            :to="{ name: 'sellOrderDelete', params: { 
                                id: slotProps.resource.id 
                                } }"
                            v-if="Auth.can('DeleteSellOrder')"
                        >
                            <font-awesome-icon icon="trash" class="align-middle">
                            </font-awesome-icon>
                            <span>{{ __("words.delete") }}</span>
                        </router-link>

                        <router-link
                            class="btn-orange"
                            :to="{ name: 'sellOrderShow', params: { 
                                id: slotProps.resource.id 
                            } }"
                            v-if="Auth.can('ShowSellOrder')"
                        >
                            <font-awesome-icon icon="eye" class="align-middle">
                            </font-awesome-icon>
                            <span>{{ __("words.show") }}</span>
                        </router-link>
                    </template>
                </sell-order-table>

                <pagination 
                    :meta="this.$store.state.sellOrder.resources.meta" 
                    @paginate="paginate"
                ></pagination>
            </div>
        </div>
    </div>
</template>

<script>
import { mapGetters, mapState } from "vuex";

export default {
    name: "sellOrderIndexPage",

    computed: mapState(["resources", "loading", "query"]),

    methods: {
        checkResource(resource) {
            return this.$store.dispatch("sellOrder/checkResource");
        },
        getResources() {
            this.$store.dispatch("sellOrder/fetchResources");
        },

        paginate(page) {
            debugger;
            let query = {
                page: page,
                title: this.$store.state.sellOrder.query.title
            };
            this.$store.dispatch("sellOrder/setQuery", { 
                query: query 
                });
            this.$router.push({ 
                name: "sellOrderIndex", 
                query: query 
            });
        },

        search() {
            this.$router.push({ 
                name: "sellOrderIndex", 
                query: this.store.query 
            });
        },
        reset() {
            this.$store.dispatch("sellOrder/resetState");
        }
    },

    created() {
        if (this.$route.query.page) {
            this.$store.state.sellOrder.query.page = this.$route.query.page;
        }
        if (this.$route.query.title) {
            this.$store.state.sellOrder.query.title = this.$route.query.title;
        }
        this.getResources();
    }
};
</script>

I'm encountering an issue where when I click on the second page, the URL changes to /sell-order?page=3, but the submitted request URL remains as /sell-order, and parameters are not being submitted in Axios.

Can someone help me identify where I might be making a mistake?

Answer №1

When working with Vuex, it's important to note that actions and mutations are pure functions, meaning they are not tied to any specific this context. Instead, the context is passed as the first argument of the function. To access values from this context, you can destructure the object in a clean and concise way:

fetchData({ commit, state })

This allows direct access to the state property without needing to use the this. prefix.

.post(route("user_data.index"), { params: state.userInfo })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Express: using async and await leads to an error when attempting to access "result" before it has been initialized

When using the login function that utilizes ExecuteSQL to validate user existence, an error occurs during file execution related to async await. ReferenceError: Cannot access 'result' before initialization at /Users/naseefali/Documents/Projects ...

XMLHttpRequest Error: The elusive 404 code appears despite the existence of the file

This is the organization of my project files: The folders Voice, Text, and Template are included. https://i.stack.imgur.com/9un9X.png When I execute python app.py and navigate to localhost http://0.0.0.0:8080/, the index.html page is displayed with conte ...

Ensure Vue line chart stays current with data passed in as props

Vue 2.x chart-js: 2.x vue-chartjs: 3.x I am currently working on a project where I need to send data from a websocket in my parent component to a child component to create a dynamic line chart that updates in real-time. In my Parent.vue file: <templ ...

Step-by-step guide to making a personalized mesh in Babylon.js

Currently, I am utilizing the Babylonjs 3D WebGL library and finding it to be a fantastic tool. However, I am facing a challenge in replicating a feature that exists in the THREE.JS library. My scenario involves 2D polygons stored in a database. I retriev ...

Tips for fixing a missing page issue in an Angular 2 boilerplate

Recently, I started exploring Angular 2 and decided to clone the repository from this link: https://github.com/AngularClass/angular-starter. My goal was to add a new menu option called 'list'. After creating the necessary component and updating t ...

Tips for creating a well-written piece of writing

sendoptions ={method : "PUT", credentials: 'same-origin', header :{"Content-Type":"application/json"}, body: JSON.stringify(Cookies.get("accessToken")} } body: JSON.stringify(Cookies.get("accessToken ...

Tips for transferring a value from a function in ASPX to a CS file

I seem to be overlooking a small detail. I have a dropdown list (DDL) and a function in my C# file. I want to pass the 'value attribute' of a selected DDL option to my function, but I can't seem to retrieve the value attribute. I checked the ...

I must automate the process of navigating to a different page within my website

My current dilemma involves using the header() function in PHP to automatically redirect a user to another page on my site after they dismiss an alert() box. However, the desired outcome is not being met. Here are my requirements: 1) Display a JavaScript ...

Ways to transfer data from one page to another using AngularJS

Hey everyone, I could really use some assistance with AngularJs. My code is quite lengthy, so I have uploaded a document file for you to review. The code snippet below shows my authentication process for email and password. The customerlogin() method retur ...

Craving assistance in coding permutations

Thank you for responding. I want to express my gratitude for your efforts in trying to assist me. Unfortunately, I have posted this problem on multiple websites and no one has been willing to help. Regarding my code, my objective is to count permutations. ...

Using dynamic names with Vue.js v-for

I am facing a challenge with my component as it needs to accept JSON data without knowing the array name or field names in advance. For example: "user": [ { "id": "1", "userid": "<a href="/cdn-cgi/l/email-protection" class="__ ...

Building a React.js application and fetching information with Ajax

In my quest to create a high-speed React.js application that functions as a game, I find myself in need of displaying real-time data. However, the traditional method of loading this data from the server using Ajax doesn't quite align with the reactive ...

A step-by-step guide to creating a custom JavaScript/AJAX function

Hello everyone, I am new to the world of Ajax and JavaScript, so please bear with me as I ask my question. I have a link on my website that opens a new window using JavaScript. In this new window, I have a form that submits data to my database using PHP. ...

How to add values at a particular index within an array using JavaScript

First, I start by creating an array with a specific size. $("#bntSize").one('click', function(e){ var memory = $("#memory").val(); console.log(memory) html = ""; for(var i = 0; i < memory ; i++){ ...

When updating the location.hash property via a click event, it appears to be set to

Check out the code snippet below: $(e).click(function() { console.log(this.href); location.hash = this.href; }); In this code snippet, e refers to a <li> element structured like this: <li href="#about">About</li> The location. ...

Tips for fixing the $injector problem in AngularJS

Recently, I started learning AngularJS and attempted to build a simple web page based on some tutorials. The page consists of two parts: one for user input using HTML and the other with JavaScript containing an if-else statement. However, I kept encounteri ...

Showcasing interactive column titles by employing angularjs in an html table

After preparing my data, I aim to showcase it in an HTML table. However, a complication arises each time the $http service is called as it returns a varying number of columns (n). Essentially, I wish to have the first row of the data serve as column names, ...

Changing the route in Vue2 depending on the value stored in the store

I have a scenario where I need to dynamically change the route of my components based on a value stored in the vuex store. There are multiple template files located in separate directories (template1, template2 etc). The template id is retrieved from the d ...

Decrease the space between slide items by reducing margins or increasing their width

I'm having trouble achieving the desired spacing between items, I would like more space between each item but they are currently too close together. I am looking for a margin of 10px or a width of 32% for each item. I have already looked into some re ...

When you include ng-href in a button using AngularJS, it causes a shift in the alignment of the text within the button

Recently, I've been delving into Angularjs with angular-material and encountered a slight issue with ng-href. I created a Toolbar at the top of my webpage, but the moment I include the "ng-href" attribute to a button, the text inside the Button loses ...