[Vuejs]-Passing a form value to build a Rest API url in Vue.js

0๐Ÿ‘

the console is executing different time because on top of your code you are using if statement if userId.length !=0 then on each key enter it will send request.please donโ€™t use this if statement

0๐Ÿ‘

  • Button to send the request is a good idea, use that.(other
    options could be keyup event, debounce if a button is too much).
  • Change the v-if to something more concrete like test for
    user !== null since user is default as null.
  • Check for a validation for a number input only when calling the
    method from the button that makes sure that you intended the input to
    be number and api is called only with a valid input.

Can try this:

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

<script>
  import axios from "axios";
  export default {
    name: "FindUser",
    data() {
      return {
        user: null,
        userId: ""
      };
    },
    methods: {
      getUser(event) {
        /*Check for validations on input and then call 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 needed to clear the userId*/
              this.userId = "";
            });
        } else {
          /*input value is not a number -do something about it (alert/notify)*/
          this.userId = "";
        }
      }
    },
    mounted() {
      // this.getUser();
    }
  };
</script>

Leave a comment