Creating a Rest API URL in Vue.js by extracting form values

I just finished coding this Vue component:

<template>
  <div>
    <h2>Search User By ID</h2>
    <input v-model="userId" type="number" placeholder="modify me" />
    <br />
    <p v-if="userId.length != 0">
      The User is: {{ getUser(userId) }}
      <!-- returns nothing...-->
      <br />
      {{ user["id"] }} {{ user["email"] }} {{ user["username"]
      }}<!-- returns object-->
    </p>
  </div>
</template>

<script>
  import axios from "axios";
  export default {
    name: "FindUser",
    data() {
      return {
        user: null,
        userId: ""
      };
    },
    methods: {
      getUser(userId) {
        axios
          .get("http://localhost:4000/api/users/" + this.userId)
          .then(response => {
            console.log(response);
            this.user = response.data.data;
          });
      }
    },
    mounted() {
      // this.getUser();
    }
  };
</script>

Although this code is functioning, there are a few issues that I need to address:

  • If I enter an ID that doesn't match any user, the previous result is not cleared
  • It would be better to have a button for sending the request
  • Another concern is that the request seems to be repeating, as evidenced by multiple displays of console logs

Answer №1

Execution timing varies on the console due to the if statement at the beginning of your code. If userId.length is not equal to 0, a request will be sent for every key press. Avoid using this if statement for smoother execution.

Answer №2

  • Utilizing a button to submit the request is a smart suggestion, make sure you implement it. (Alternatively, consider using the keyup event or implementing debounce if a button seems excessive).
  • Replace the current v-if with a more specific condition like checking for user !== null since the default state of user is null.
  • When triggering the method from the button, include validation for a number input to ensure that the intended data type is submitted and the API is only called with valid input.

You can experiment with this:

<template>
  <div>
    <h2>Search User By ID</h2>
    <input v-model="userId" type="number" placeholder="edit me" />
    <!--@click shorthand for v-on:click-->
    <button @click="getUser($event)">Find User</button>
    <br />
    <p v-if="user !== null">
      The User is : {{ displayWhateverHere }}
      <br />
      {{ user["id"] }} {{ user["email"] }} {{ user["username"] }}
    </p>
  </div>
</template>

<script>
  import axios from "axios";
  export default {
    name: "SearchUser",
    data() {
      return {
        user: null,
        userId: ""
      };
    },
    methods: {
      getUser(event) {
        /*Validate the input before calling the API*/
        let validFlag = !isNaN(this.userId);
        if (validFlag) {
          axios
            .get("http://localhost:4000/api/users/" + this.userId)
            .then(response => {
              console.log(response);
              this.user = response.data.data;
              /*If required, reset the userId field*/
              this.userId = "";
            });
        } else {
          /*Handle scenario where the input is not a number (e.g., alert/notify the user)*/
          this.userId = "";
        }
      }
    },
    mounted() {
      // this.getUser();
    }
  };
</script>

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

Internet Explorer causing trouble with reliable Ajax dropdown selection

There are two drop-down lists on my website, where the options in one depend on the selection in the other. The Ajax code works perfectly fine in Chrome and Mozilla, but it's not functioning correctly in Internet Explorer (specifically IE9). I need so ...

Ensure that all items retrieved from the mongoDB query have been fully processed before proceeding further

In the midst of a challenging project that involves processing numerous mongoDB queries to display data, I encountered an issue where not all data was showing immediately upon page load when dealing with large datasets. To temporarily resolve this, I imple ...

How can we maintain reactivity while updating the entire object from the server in Vue.js 2?

I have a list of items that are initially loaded with just id and name from the database. However, upon clicking on an item, additional fields can be fetched dynamically, and these fields can vary in length. While updating an item, I encountered reactivi ...

The Formik form is not being populated with data from the API

While working on a functional component in ReactJS, I created a simple form using Formik. The input fields in my form are supposed to fetch data from an API when the component mounts. To achieve this, I utilized fetch and useEffect. However, after fetching ...

Ways to retrieve the content from a textfield

Is there a way to retrieve text from a textfield in material UI without using the onChange method? It just seems odd that I would need to constantly track the value with onChange in order to use it for any other purpose. I decided to search for solutions ...

Relocate the preview division below the button in the Kartik File Input Widget

There are two input file buttons that allow users to upload an image on each button. Upon selecting an image, a preview of the image will be displayed above the button. The current layout is shown here: https://i.sstatic.net/aLAbo.png When images of diff ...

Stopping errors are a common occurrence in synchronous AJAX

I recently encountered an issue with my AJAX request setup. In the success callback function, I called a new function to render Google links and made another AJAX call. To address some performance concerns, I attempted to change these asynchronous calls t ...

Unlocking $refs with the Composition API in Vue3 - A step-by-step guide

I am currently exploring how to access $refs in Vue 3 using the Composition API. In my template, I have two child components and I specifically need to obtain a reference to one of them: <template> <comp-foo /> <comp-bar ref="ta ...

Utilizing Angular Forms for dynamic string validation with the *ngIf directive

I have a challenge where I need to hide forms in a list if they are empty. These forms contain string values. I attempted to use *ngIf but unfortunately, it did not work as expected and empty fields are still visible in the list. How can I address this iss ...

Delegate All Events to the Document

In my current setup, I have over 350 events that look like: $(document).on('click','.removable-init',function(){}); I've noticed a performance issue where some click events are delayed by a fraction of a second. This is happening ...

Using JavaScript to ensure that a div is not hidden on page load if a checkbox is unchecked

Upon inspecting a page, I am implementing a script to check if a checkbox is selected. If not selected, the goal is to hide a specific div element. While troubleshooting this issue, I suspect the problem may be due to the lack of an inline element within t ...

Exploring the mechanics behind ES6 Map shims

From what I've gathered from the documentation (here and here), it seems that having a reference to the memory address is necessary for the operation to work: const foo = {}; const map = new Map(); map.set(foo,'123'); // This action requi ...

What steps should be taken once the idToken in Firebase has expired?

My code is utilizing the onAuthStateChanged function: this.unregisterAuthObserver = firebase.auth().onAuthStateChanged(user => { if (user) { user.getIdToken(true).then((idToken) => { console.log(user) ... }); } After the idT ...

Resolving issues with CSS placement and resizing

I have been considering developing a UI toolkit that offers an intuitive and powerful way of setting the position and size of elements/widgets. Here are some examples of how it could be used (although they are not currently implemented): ui("Panel").size( ...

What is the best way to transform an HTML <script> tag into React code?

I am new to the world of JavaScript and React. Can someone help me convert the script below into a React component? <div id="SOHUCS" sid="xxx"></div> <script charset="utf-8" type="text/javascript" sr ...

Issue with Achieving Two-Way Binding in Angular 1.5 Component when using $ctrl

I am struggling with customizing some products using a component in my index.html. Ultimately, I need to calculate the total of selected products within the main controller "planosVoz" using two-way binding on the svaTotal property in the component control ...

Steps for resetting a div's display after adjusting the device size

I have a code that displays horizontally on desktop screens and vertically on phones. It includes an x button (closebtn) that is only displayed on phones to close the menu bar. How can I automatically display it again after resizing the page back to deskto ...

A reliable approach for dynamically altering SVG graphics

It seems like IE10 does not support CSS transformations for SVGs, only attribute transformations. Here is an example: <svg><rect id="myrect" width="200" height="200"></rect></svg> setTimeout(function() { var r = document.getE ...

When transmitting information to the server, the browser initiates four requests

I am encountering an issue with my React component. The problem arises when I try to retrieve the current geographic coordinates, as they are being fetched 4 times consecutively. This same glitch occurs when attempting to send the coordinates to the serv ...

Why isn't my code able to locate the navigation partial?

Here is my contact.ejs file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title>Title</title> <style> body { background: skyblue; font-family: verdana ...