What is the best way to find information through the API?

As a newcomer to Vue.js, I decided to take on a project that involved utilizing an API. The initial version of this project was created by TraversyMedia using React, but I saw potential in converting it to Vuejs as it looked simple enough. However, I am encountering difficulties when trying to search the API for specific actors. Although the search bar registers user input, I am facing challenges in querying the API efficiently.*

<template lang="">
    <div>
        <!-- Breaking Bad -->
        <Header></Header>
        <Search v-on:wordChange="onWordChange"></Search>
        <ActorList v-bind:characters="actorInfo"></ActorList>
        <!-- characters is the name of the property we want to show up in the child component -->
        <!-- {{ actorInfo.length }} -->
        <Actor></Actor>
    </div>
</template>
<script>
    import Header from "./components/Header";
    import Search from "./components/Search";
    import ActorList from "./components/ActorList";
    import Actor from "./components/Actor";
    import axios from "axios";

    export default {
        name: "App",
        data: function() {
            return { actorInfo: [] };
        },
        components: {
            Header,
            Search,
            ActorList,
            Actor
        },
        mounted() {
            axios
                .get("https://www.breakingbadapi.com/api/characters?name", {})
                .then((response) => {
                    this.actorInfo = response.data;
                    // this.datas = response.data;
                    // console.log(response.data);
                })
                .catch(function(error) {
                    console.log(error);
                });
            //This is how to get all data from the api endpoint with axios
        },
        methods: {
            onWordChange: function(searchTerm) {
                console.log(searchTerm);
            }
        }
    };
</script>
<style>
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        font-family: "Montserrat";
        font-size: 15px;
        color: white;
        background: rgb(0, 0, 0);
        background: linear-gradient(
            90deg,
            rgba(0, 0, 0, 1) 0%,
            rgba(2, 44, 23, 1) 33%,
            rgba(2, 44, 23, 1) 66%,
            rgba(0, 0, 0, 1) 100%
        );
    }
</style>

Answer №1

When you place the axios request inside the mounted hook, it will only execute once when the component is mounted to the DOM. This means that nothing will happen as you type because the request is not triggered again.

I suggest two options to address this issue:

Option 1: Query the API once on page load and perform local searching on the client-side.

This approach allows for fast searching without querying the API repeatedly. You can control how the records are matched against your query. However, if new data is added to the API, you will need to refresh the page to see and search the updated information. It seems like this aligns with your current goal.

If this is the case, you can use a computed property to display the filtered results from a query while utilizing this.actorInfo to store the full list of searchable records:

<template>
  <div>
    ...
    <Search v-on:wordChange="onWordChange"></Search>
    <ActorList v-bind:characters="filteredResults"></ActorList>
    ...
  </div>
</template>

<script>
  ...

  export default {
    ...
    data () {
      return {
        actorInfo: []
      }
    },
    mounted () {
      axios.get('https://www.breakingbadapi.com/api/characters?name')
        .then(response => {
          this.actorInfo = response.data
        })
    },
    computed: {
      filteredResults () {
        return this.actorInfo.filter(actor => {
          // Implement your own custom search algorithm here if needed
          return actor.toLowerCase().startsWith(this.searchTerm.toLowerCase())
        })
      }
    },
    methods: {
      onWordChange (searchTerm) {
        this.searchTerm = searchTerm
      }
    }
    ...
  }
</script>

Option 2: Query the API on every keystroke.

This method provides real-time access to new API data but may result in latency between keystrokes. There's also a risk of getting rate limited by the server due to frequent requests, and you have less control over how records are matched against the query.

To implement this, create a new method called search that performs an HTTP request based on the search term. Initially, call this method with an empty string in the mounted hook to load all records. Subsequently, each keystroke triggers a request with the input value to fetch filtered results.

<template>
  <div>
    ...
    <Search v-on:wordChange="onWordChange"></Search>
    <ActorList v-bind:characters="actorInfo"></ActorList>
    ...
  </div>
</template>

<script>
  ...

  export default {
    ...
    mounted () {
      this.search('') // This loads all records on page load
    },
    methods: {
      onWordChange (searchTerm) {
        this.search(searchTerm)
      },
      search (searchTerm) {
        axios.get('https://www.breakingbadapi.com/api/characters?name=${searchTerm}')
          .then(response => {
            this.actorInfo = response.data
          })
      }
    }
    ...
  }
</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

The Parcel build was unsuccessful due to an error from @parcel/resolver-default: The file '../../../../../css/main.css' could not be loaded within the './src' directory

I utilize [email protected]. Whenever I attempt to load an external css or javascript file in my index.html, Parcel consistently fails to build with the following error: Build failed. @parcel/core: Failed to resolve './css/main.css' from & ...

Perform the function prior to making any adjustments to the viewmodel attributes

Within my view, I am showcasing employee details with a checkbox labeled Receive Daily Email. When a user interacts with this checkbox, I want to trigger an AJAX function to validate whether the user is allowed to modify this setting: If the result is tru ...

Is it the browser's responsibility to convert ES6 to ES5 internally?

Given the support for ES6 in modern browsers, do they internally convert ES6 to ES5 before executing the code? Or can they process ES6 natively using a C++ engine? If they are able to run ES6 directly, how do they guarantee that executing ES6 code produce ...

The class .is-invalid transforms into .is-valid when rendered

Currently, I am incorporating bootstrap into my react project. In this case, I have a variable called mobile that needs to undergo validation whenever there is a change in the input field. Below is the code snippet for the component: const EnterMobile = ( ...

Exploring the process of integrating pagination into vue.js

Currently, I am facing difficulties with implementing pagination in vue.js. I have written the necessary vue.js script and template for this functionality, but unfortunately, the pagination feature is not working as expected. Despite numerous attempts to ...

Hide the Select Column from the material-react-table

Can someone help me with hiding specific columns in the material-react-table component? I've searched the documentation but couldn't find any relevant information. import { useMemo, useState } from "react"; import { MaterialReactTable } ...

Getting the value of a CSS Variable from Radix UI Colors with Javascript/Typescript: A step-by-step guide

Currently, I am attempting to dynamically retrieve the Radix Colors values in JavaScript. The reason for this requirement is that I generate these colors based on user input, resulting in values that are variable. As a result, I cannot hardcode the values. ...

How can an object inside an array be destructured in just one line?

Consider the following array: const array = [{b:2}] Can you extract the value of b using destructuring in just one line? I attempted something similar to this approach, but it did not yield the desired result: const [{b} = array] ...

click event to activate delayed function in dropdown

Within the li element, there is an onclick function with a data-toggle="dropdown" attribute. The issue at hand is that my function isn't triggered when I click once, but interestingly it works after clicking twice. https://i.sstatic.net/GdvoT.png I ...

Identify and react to an unexpected termination of an ajax upload process

My ajax uploading code can determine if a file was successfully uploaded only after the upload has completed. If the upload is terminated before completion, no data is returned. Is there a way to detect when an upload is unexpectedly terminated and alert t ...

How can I extract the value of a JavaScript variable using jsoup in an HTML document?

<html> <script type="text/javascript"> var map = null; jQuery(function($) { L.marker([50.065407, 19.945104], {title: 'Cat'}) .bindPopup('<h3>Cat</h3> ...

Is there a way to identify the subdocument ids that have been updated in Mongoose when performing an

Is there a reliable way to retrieve the _id of subdocuments that are inserted into an array within my document using doc.updateOne? I am concerned about getting incorrect _id values when multiple updates occur. This is my current approach, but I'm wo ...

JavaScript Fullcalendar script - converting the names of months and days

I recently integrated the Fullcalendar script into my website (https://fullcalendar.io/). Most of the features are functioning correctly, however, I am seeking to translate the English names of months and days of the week. Within the downloaded package, ...

Issue with rendering components list in React.js

I am currently working on a project using React, and I'm facing an issue where my list is not displaying on render(). In my parent component, I have a list of components coming from SearchResult. Below is the relevant portion of my code: class Create ...

Setting the row ID value after performing form editing in free jqGrid

In the table, there is a primary key with 3 columns (Grupp, Kuu, Toode), and the server returns an Id created from those columns. When the primary key column is changed in form editing, the server sends back a new row id. However, Free jqgrid does not se ...

Traversing through nested arrays within nested objects using AngularJS

In my project, I am utilizing angularjs 1 and dealing with a complex json object that has multiple levels of nesting. My goal is to use ng-repeat in order to access a nested array within the json structure. [{ "information": { "name": "simdi jinki ...

Is it possible for a function within a nodejs module to be defined but display as undefined upon access?

I am currently developing a Discord bot using NodeJS and TypeScript, and I'm facing an issue while trying to import custom modules in a loop with the following code: const eventFiles = fs.readdirSync("./src/events/").filter((file: string) =& ...

Unable to deserialize an instance of java.util.List from the VALUE_STRING

In the process of developing a new application, my goal is to send data to a server and receive a response in a specific format. Here's an example of how the format should look: { "userName" :"<a href="/cdn-cgi/l/email-protection" class="__cf_e ...

A guide on implementing the stencilFunc method in Three.js

Is it possible to utilize stencilFunc and stencilOp functions within Three.js? I attempted to incorporate code for a stencil test but encountered issues. var scene = new THREE.Scene(); var renderer = new THREE.WebGLRenderer({ antialias: true, st ...

Incorporating Hyperlinks into Text using React I18next

I'm facing an issue with I18next. I can't seem to make links to websites work correctly using the following code: import React, { Suspense } from "react"; import i18n from "i18next"; import { initReactI18next, useTranslation, ...