Tips on choosing filters and leveraging the chosen value for searching in a Vue application

I am currently working on a Vue JS application that allows users to apply filters and search a database. The user can select or type in filters, such as "to" and "from", which are then used in a fetch URL to retrieve data from a json-server. Once the user selects the filters, they can click a button to apply them and retrieve messages from the server.

Below is the relevant code snippet:

    <template>
    <v-app>
     <v-autocomplete dense
          filled
          label="From: "
          v-model="selectedFrom"
          :items="msgFromID"
          item-text='MsgFrom'
          item-value='MsgFrom'>
    </v-autocomplete>
    <v-autocomplete dense
          filled
          label="To: "
          v-model="selectedTo"
          :items="msgToID"
          item-text='MsgTo'
          item-value='MsgTo'>
    </v-autocomplete>

    <v-btn @click="fetchData()">Apply Filters</v-btn>
   </v-app>
   </template>

   <script>
export default {
    name: 'Inbox',
    data() {
        return {
            msgFromID: [],
            msgToID: []
   }
 },  
 mounted() {
        fetch('SAMPLEURL/messages?MsgFrom=')
            .then(res => res.json())
            .then(data => this.msgFromID = data)
            .catch(err => console.log(err.message)),
            fetch('SAMPLEURL/messages?MsgTo=')
                .then(res => res.json())
                .then(data => this.msgToID = data)
                .catch(err => console.log(err.message)),
 },
methods: {
        fetchData(selectedTo, selectedFrom) {
            fetch('SAMPLEURL/messages?MsgFrom=' + selectedFrom + '&MsgTo=' + selectedTo)
                .then(
                    function (response) {
                        if (response.status !== 200) {
                            console.log('Looks like there was a problem. Status Code: ' +
                                response.status);
                            return;
                        }
       }

However, whenever I click the "Apply Filters" button, the values don't get saved and I end up with an undefined URL in the log:

    SAMPLEURL/messages?MsgFrom=undefined&MsgTo=undefined

I need help resolving this issue so that the selected values do not show up as undefined. Additionally, I would like to know if it's possible to ignore one of the search criteria (MsgFrom or MsgTo) if no value is selected by the user?

Answer №1

Your click-binding does not include any parameters:

<v-btn @click="fetchData()">

However, the method expects two parameters:

export default {
  methods: {
    fetchData(selectedTo, selectedFrom) {/*...*/}
  }
}

Since no arguments were passed to the method, the values of selectedTo and selectedFrom are undefined, resulting in the error that occurred.

Solution

You can either update the binding to pass the required parameters:

<v-btn @click="fetchData(selectedTo, selectedFrom)">

Alternatively, you could modify the method to utilize the component's data props:

export default {
  methods: {
    fetchData() {
      const { selectedTo, selectedFrom } = this
      fetch('SAMPLEURL/messages?MsgFrom=' + selectedFrom + '&MsgTo=' + selectedTo)
      //...
    }
  }
}

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

Tips on accessing the v-model value with a parameter in VUE

Looking to access the v-model value using a parameter, I attempted the following code: <template> <div v-for="(item, idx) in data"> <input :id="item" :v-model="item"></input> <button @click=&q ...

Explore how Next.js's getServerSideProps feature incorporates loading animations and improves

I have implemented getServerSideProps in my project's pages/post/index.js file: import React from "react"; import Layout from "../../components/Layout"; function Post({ post }) { console.log("in render", post); return ( <Layout title={pos ...

When a form contains a ViewChild element, changes to the ViewChild element do not automatically mark the

Let's set the stage: MainComponent.html <form #someForm > <input type="text" name="title" [(ngModel)]="mainVar" /> <child-component /> <input type="submit" [disabled]="someForm.form.pristine" /> </form> ChildComp ...

Are the server updates not syncing with the client browser?

Is there a reason why server updates are not appearing on the client browser? Could it be that a specific attribute value needs to be modified or is this related to caching? app.get('/hello' , (_ , res) => { res.header({ 'Cach ...

Tips for validating form input upon submission in Angular 6

Within my Angular application, I have successfully implemented form validators. However, I am aiming to trigger form validation specifically upon submission. This means that when the user clicks on the submit button and the form is invalid, the errors indi ...

Utilizing 'nestjs/jwt' for generating tokens with a unique secret tailored to each individual user

I'm currently in the process of generating a user token based on the user's secret during login. However, instead of utilizing a secret from the environment variables, my goal is to use a secret that is associated with a user object stored within ...

A guide to replicating HTML using AngularJS

I am attempting to replicate HTML content using AngularJS. While I was successful using jQuery, it caused conflicts with Angular. Therefore, I aim to achieve the same result using AngularJS. Here is the code I have written: function printContent(el){ ...

When utilizing MUI's ThemeProvider, it may result in encountering errors that display as "undefined"

I am facing an issue with my MUI application. Everything was working perfectly until I decided to implement a ThemeProvider. It seems that as soon as I add the ThemeProvider, the application breaks and all MUI components I'm using start throwing undef ...

` `Spinning graphics and written content``

I am looking to create a dynamic element on my website where an image and corresponding text block rotate every few seconds. An example of what I am envisioning can be seen on this website: While I know how to implement a javascript for rotating images, I ...

The absence of the dark class in the body is still allowing the impactful influence of Tailwind

I set up a ThemeContext in my NextJS project to switch between light and dark themes on my website. However, I encountered an issue where elements that have the "dark:" prefix in their class names apply the dark theme instead of the initial light theme whe ...

Incorporate a collection of product titles along with their short forms in JavaScript/jQuery

Seeking guidance as a newcomer to JS. I have encountered the need for two different views in an application I am working on - one displaying full product names and the other showing only their abbreviations. Instead of hard-coding this information, I wish ...

Is it necessary to clean and reinstall node_modules every time I deploy in a production environment?

We manage over 10 production servers and each time we update our dependencies, performing a clean installation seems more controlled but also slower. The issue is that the devops team is concerned about the time it takes to perform a clean npm install aft ...

What are the best practices for storing an array of objects in MongoDB with Mongoose?

For my project, I needed to store data in a mongoDB document as an array of objects using Javascript, Node JS, Express framework, and Mongoose library. After researching online, I found two different methods to achieve this: Creating another sub-schema ...

What is the best way to distinguish a particular item in a <select> element and include a delete button for each row using jQuery?

1.) I've set up a nested table and now I want to ensure that when the 'Delete' button within the child table is clicked, its corresponding row gets deleted. 2.) I have a <select> tag. The issue is how can I implement validation to che ...

The Best Approach for Angular Google Maps Integration

I'm diving into Angular for the first time while working on a project that requires advanced mapping functionality like clustering, routing, road routing, paths, directions, polygons, events, drawing on maps, info windows, markers, etc. After some re ...

Are there any other benefits to utilizing the Decorator pattern besides enhancing dynamic behavior?

Currently, I am diving into the intricacies of the Decorator design pattern and a particular thought has been nagging at me. What if we simply had one base class with boolean values representing its features? Consider this example: Imagine a textview tha ...

Exploring the process of web scraping from dynamic websites using C#

I am attempting to extract data from using HtmlAgilityPack. The website is dynamic in nature, displaying content after the page has fully loaded. Currently, my code retrieves the HTML of the loading bar using this method, but encounters a TargetInvocation ...

Running a code from a plugin in Wordpress site

I am currently utilizing the "wp-video-lightbox" plugin for WordPress, which generates small floating boxes for my videos. I am interested in incorporating variables like http://www.example.com/?video3 to provide shortcuts similar to what YouTube offers. ...

Issue with invoking controller action in MVC4 via AJAX

Below is the method in my controller: public JsonResult GetRights(string ROLE_ID) { var result = db.APP_RIGHTS_TO_ROLES.Where(r => r.FK_ROLE_ID.ToString() == ROLE_ID).Select(r => r.APP_RIGHTS).ToList(); return Json(re ...

Tips for adjusting the border color of a MUI Select field

https://i.stack.imgur.com/rQOdg.png This MUI select box changes color from blue to black based on selection. The challenge is to customize the text and border color to white (currently set as blue). Any suggestions on how to achieve this? ...