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

Ways to prevent my website from being accessed through the Uc Browser

Is there a way to prevent my website from functioning on UC Browser using HTML or JavaScript? ...

Using Vuetify to submit form data using Axios

Utilizing Vuetify in my VueJs application, I am trying to send data from a form that includes file (CSV) uploads and various number inputs. My goal is to achieve this using Axios. Despite several attempts, I keep encountering a 404 error. This snippet sh ...

Create an animation effect where a div increases in height, causing the divs beneath it to shift downward in a

My aim is to create columns of divs where the user can click on a div to see more content as the height expands. I've managed to set this up, but it seems there's an issue with the document flow. When I click on a div in the first column, the div ...

The loading icon in JavaScript failed to function when JavaScript was disabled in the browser

On my blogger website, I tried using JavaScript to display a loading icon until the page completely loads. However, this method did not work when JavaScript was disabled on the browser. Only CSS seems to provide a solution. document.onreadystatechange = ...

Is using setTimeout in a group of promises blocking in JavaScript?

Is it possible for multiple requests to be queued up and executed in sequence when calling the function func? The third promise within func includes a lengthy setTimeout that can run for as long as 3 days. Will additional calls to func trigger one after an ...

Arrange a div element within another div by utilizing the fixed positioning property, while also accounting for any potential "white space

Can someone help me figure this out: I currently have this much progress: http://jsbin.com/apikiw/3/edit#preview The issue I'm facing is that I am unable to insert it between the <p /> tags due to its dynamic nature... any solutions or suggest ...

What is the method for closing an <iframe> element directly?

A web page called room.html contains a table with an onclick function named place(): function place() var x = document.createElement("IFRAME"); x.setAttribute("src", "loading.html"); document.body.appendChild(x); } What is ...

Switch on and off the active class in child components using VueJS

I'm currently working on an explore page in VueJS that includes child components called toggle-tiles, which are displayed as grids. The goal is to apply an active class when a "toggle-tile" is clicked, but only one can be active at a time. Right now, ...

The consistency of values remains constant throughout all Ajax requests

I am presenting the code snippet below: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title>Document</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" ...

Changing the value of an object property (illustrated using a basic linked list)

I am working on a JavaScript Link List implementation as a beginner, and I have written the following code: var LinkList = function () { this.LinkedList = { "Head": {} }; }; LinkList.prototype = { insert: function (element) { var Node = this ...

Footer button overrides list components due to improper implementation of vertical ion-scroll

Having some trouble setting up ion-scroll on a specific screen in my mobile application built with Ionic. On the Book page of my app, I'm encountering two main issues: https://i.stack.imgur.com/MnheG.png 1) The placement of the Confirm button doesn& ...

The Mongoose .lt method is unable to process the post value

I came across this interesting Mongoose function snippet: exports.readSign = function(req, res) { if (req.user.roles.indexOf('admin') === 1) { Timesheet.find() .where('projectId').equals(req.params.projectId) ...

Targeting an HTML form to the top frame

Currently, I have a homepage set up with two frames. (Yes, I am aware it's a frame and not an iFrame, but unfortunately, I cannot make any changes to it at this point, so I am in need of a solution for my question.) <frameset rows="130pt,*" frameb ...

What is the best way to implement debouncing for an editor value that is controlled by the parent component?

Custom Editor Component import Editor from '@monaco-editor/react'; import { useDebounce } from './useDebounce'; import { useEffect, useState } from 'react'; type Props = { code: string; onChange: (code: string) => void ...

Executing axios calls within other axios calls and altering state in React before all calls have completed

Currently, I am working on implementing nested axios calls to create the desired object by making multiple API requests. However, I am facing an issue where the state updates before all requests have finished, causing my table to populate entry by entry ...

How can I specify a default variable for formatting in vue-i18n?

format const messages = { en: { message: { hello: '{msg} world' } } } usage <p>{{ $t('message.hello', { msg: 'hello' }) }}</p> <!-- I don't want to input the second param {msg: 'hell ...

Facing issues with Handsontable opening within a jQuery UI dialog?

After implementing the Handsontable plugin in multiple tables, everything appears as expected on the parent page. However, when attempting to open a dialog containing a table, the tables do not display properly (only in IE). A demonstration of this issue c ...

Concealing Navigation Links in VueJs Upon Being Clicked

I've been trying everything to get the navigation links to hide when I click on them, but so far nothing has worked. Here's a snippet from my Header.vue file: <template> <nav class="navbar is-dark is-fixed-top"> <div class="co ...

Creating a GIF file using Node.js leads to a corrupted image

I have been experimenting with creating a simple GIF. I followed the example provided in this NPM library for guidance. Despite my efforts, every time I generate the GIF, it appears as a corrupted image file. CODE const CanvasGifEncoder = require('ca ...

Completing the regex properly

When using my editor, I am able to paste a video URL which is then converted by regex into an embed code. The URL in the WYSIWYG-editor looks like this: Once converted, the output HTML appears as: <p>http://emedia.is.ed.ac.uk:8080/JW/wsconfig.xml& ...