Utilizing Multiple Filters in Vue.js Across Various Modals

I created a dynamic web application using Vue.js and Flask that allows for CRUD operations. The app utilizes axios for making API requests. One of the core components of my application fetches data from a database and presents it in a table format. To retrieve all records from the database, I use the base path:

localhost:5000/expenses

In order to filter the displayed data, I implemented two buttons that trigger modals. The first modal requires users to input a start date and an end date, which then sends a GET request to:

localhost:5000/expense?startDate=2020-04-10&endDate=2020-04-21

The backend, powered by Flask, filters the data based on the specified date range before returning it to be shown in the table.

The second modal provides a dropdown menu for selecting a category to filter the data further. This second GET request only queries the backend at:

localhost:5000/expense?category=food

To combine both filtering options in the GET request URL, the desired format would be:

localhost:5000/expense?startDate=2020-04-10&endDate=2020-04-21&category=food

The method responsible for sending the GET request is called getExpenses() and accepts three named parameters:

getExpenses({  
  filteredCategory,  
  filteredStartDate,  
  filteredEndDate,  
} = {}) {  
  const path = 'http://localhost:5000/expenses';  
  axios.get(path, {  
    params: {  
      category: filteredCategory,  
      startDate: filteredStartDate,  
      endDate: filteredEndDate,  
    },  
  })

This method is invoked independently when each modal form is submitted:

onSubmitCategory(evt) {
  evt.preventDefault();
  this.$refs.addCategoryModal.hide();
  const filteredCat = this.addCategoryForm.category;
  this.getExpenses({
    filteredCategory: filteredCat,
  });
  this.initForm();

onSubmitDate(evt) {
  evt.preventDefault();
  this.$refs.addDateRangeModal.hide();
  const filtStartDate = this.addDateRangeForm.startDate;
  const filtEndDate = this.addDateRangeForm.endDate;
  this.getExpenses({
    filteredStartDate: filtStartDate,
    filteredEndDate: filtEndDate,
  });
  this.initForm();

How can I preserve the state to enable filtering on top of previously filtered data? Is there a way to maintain state even after page refresh so that the last query isn't lost? Currently, upon refreshing, the page defaults back to the base path and displays all data instead of retaining the previous filter. Any suggestions are appreciated!

Answer №1

Utilizing vue-router can improve the efficiency of handling queries.

In my implementation, I opted to utilize lodash for selectively querying data.

mounted() {
    this.getExpenses();
},

methods: {
    // Function to make axios GET request
    getExpenses() {
        axios.get(path, this.getRequestQuery()).then((res) => {
             // Response handling code goes here
        }).catch((e) => {
             // Error handling code goes here
        })
    },

    // Invoke search on filter change event or place filters in a form and trigger search on submit event
    search() {
        const query = this.mapFiltersToQuery();
        this.$router.push({ query });
    },

    // Obtain query from $route.query + filters and generate query for request
    getRequestQuery() {
        this.mapQueryToFilters();
        const query = this.mapFiltersToQuery();
        return query;
    },

    // Merge queries from $route.query and your data filters
    mapQueryToFilters() {
        this.filters = { ...this.filters, this.$route.query };
    },

    // Select specific filters from data for query construction
    mapFiltersToQuery() {
        const nonEmptyFilters = _.pickBy(this.filters, v => (!_.isEmpty(v) || !!v));
        return nonEmptyFilters;
    },
},

watch: {
    '$route.query': {
        handler() {
            this.getExpenses();
        },
        deep: true,
    }
}

Best of luck!

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

Transform a JavaScript object into an array format

I currently have an object structured as follows: {"label":["Option 1","Option 2","Option 3"],"share":[0.0650068849312104,0.00873977167120444,0.00873977167120444]} My goal is to transform this object into an array with the following format: [{label: "Op ...

Creating an app using Ionic 1 that features scrollable tabs with the ability to handle overflow

My current code snippet is displayed below. On smaller mobile screens, all 7 tabs are not visible at once and instead appear in two rows which looks messy. I want to modify the display so that only 3 tabs are visible at a time and can be scrolled through. ...

Solving SEO issues with jQuery load()

I have developed a modal window that includes links, but unfortunately, search engine crawlers are unable to read and index those links. I am looking for a solution to make sure the crawler can index those links. I have noticed websites using AngularJS li ...

I'm struggling to figure out why I can't render an HTML element in React after waiting for a promise to

In this particular scenario, the index.js file is calling upon the component DiffState.js. The purpose of DiffState.js is to simulate an asynchronous operation by waiting for 2 seconds and then returning an H1 element with the text "hello". index.js impor ...

The OnChange event seems to be malfunctioning as it is not being triggered despite other parts of the code functioning properly

Check out the code snippet below: import React, { useState } from "react"; function IP() { const [ipAddress, setIPAddress] = useState(""); const handleInputChange = (event) => { const inputValue = event.target.value; // ...

I'd really appreciate your assistance in obtaining a value for a specific webelement

I am facing an issue where I am trying to retrieve the value from a WebElement 'input'. The general method getText() doesn't seem to work for me in this case. However, when I tried using JavaScript in the console, it worked perfectly: " ...

Retrieve the current row by clicking the button

I've been struggling to retrieve a specific value from a row displayed on my PHP webpage. My objective is to obtain the current value from a particular cell in the row, but using getElementsByTagName has not been successful as it only returns an HTMLC ...

Show data in a popup using jQuery DataTables and loading content asynchronously via Ajax

I am attempting to display a list in a popup based on an Ajax request. Prior to the Ajax call, the list is contained within the popup. However, after the Ajax request, the list remains on the page instead of inside the popup, and the old list still appears ...

Is there a way to detect a class change using jQuery?

Below is an example of a div: <div id="components-reconnect-modal" class="components-connecting-show"> <div id="1"> <div id="2"> <div id="3"> <div id="4"> </div> The ID will remain constant, but the class will ...

Local variable reference getting lost in a loop during a jQuery Ajax call

Currently, I am facing an issue with my jQuery ajax calls within a loop. The problem arises when each ajax call returns and I need to retrieve a specific value associated with the original call. However, due to further iterations in the loop, the value of ...

Enabling JavaScript functions to accept a variable number of arguments

I am looking to enhance the versatility of the function below by enabling it to accept multiple callbacks to other functions if they are specified in the arguments. $(function() { function icisDashBox(colorElem, thisWidth, thisHeight, completeCallBack ...

Using httpRequest to handle binary data in JavaScript

Having trouble deciphering the response of an http request that is a binary datastream representing a jpeg image, despite numerous attempts. Edit: Including the full code snippet below: xmlhttp = false; /*@cc_on@*/ /*@if (@_jscript_versio ...

Guide to building a basic Table View for iOS with the help of HTML, Twitter Bootstrap, jQuery Mobile and more

I have experience with Objective-C, but I am still learning HTML/jQuery/JS. My goal is to create a Table view using these languages. Can anyone provide assistance by guiding me on how to achieve this? I was able to create a static Table view using the co ...

Automatically generate the first user on the Parse Server system

Is it feasible to programmatically create a User on Parse server without the need for sign up? More information can be found at https://github.com/parse-community/parse-server We attempted this using cloud code. var user = Parse.User(); user.setUserna ...

Encountering an issue with React JS Array Filtering: running into the error message "

I am encountering an error stating that includes is not a function, and the record.id is not being recognized in VS Code. I'm not sure where the problem lies? import React, { Component } from 'react' import axios from "axios" export de ...

What could be causing the fourth tab to not show any data while the first three tabs are functioning as expected?

I've encountered an issue with my HTML tabs. While I can easily switch between the first three tabs and view their content, tab 4 doesn't seem to display its associated data. It's puzzling why tab 4 is not working when the others are functio ...

Using AJAX to update the value of a div by clicking within a PHP loop

I'm currently working on a php page where I want to dynamically change the content of a div when a specific link is clicked. The links are generated through a loop, and I need to pass multiple parameters via the URL. Since the divs are also created wi ...

Unable to retrieve JSON element using Fetch

I'm attempting to retrieve a JSON file and exhibit its components within a div. Here is the JSON data I have: [ { "0":{ "host_id":"129230780", "host_names":"STK Homes", ...

Why is TypeScript giving an error about an undefined object key, even though the key was assigned a value in the previous command?

type MaybeThereIsAValue = { [p: string]: string | undefined } ... let bar: MaybeThereIsAValue = {}; const key = "carpe"; bar[key] = "diem"; const why = bar[key]; // why is string | undefined I am confused as to why why is showing ...

Is there a way to execute a condition in a Vue component before rendering the HTML in the template?

Here is an example of my Vue component: <template> <div id="modal-transaction" class="modal fade" tabindex="-1" role="dialog"> ... <div class="modal-header"> <h4 class="modal ...