What are the steps to retrieve and showcase data when a page loads and when conducting a search query

I need help with displaying data upon page load and also when searching for information.

Currently, I can only see data when I search by typing. How can I make the list of artists show up when the page loads as well?

  1. How do I show data when the page loads?
  2. How do I display data when searching?

Thank you in advance!

<template>
  <div class="body">
    <div class="searchBar">
      <i class="bi bi-search"></i>
      <input
        placeholder="Search for artists"
        type="text"
        v-model="searchQuery"
        @keyup="searchArtist"
      />
    </div>
    <div class="artists">
      <div
        className="artist__list"
        v-for="artistResult in result"
        :key="artistResult.id"
      >
        <h4>{{ artistResult.name }}</h4>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import "./body.css";
export default {
  data() {
    return {
      artists: [],
      result: [],
      searchQuery: "",
    };
  },
  mounted() {
    this.fetchArtists();
    this.searchArtist(); // Displaying data on page load
  },
  computed: {
    filteredResult() {
      const res = this.result;
      const search = this.searchQuery;
      if (!search) {
        return res;
      }
      return res.filter((item) =>
        item.name.toLowerCase().includes(search.toLowerCase())
      );
    },
  },
  methods: {
    async searchArtist() { // Function to fetch data based on search query
      try {
        const response = await axios.get(`http://localhost:3000/artists?q=${this.searchQuery}`);
        this.result = response.data;
      } catch (error) {
        console.error(error);
      }
    },
    async fetchArtists() { // Function to fetch all artists on page load
      try {
        const response = await axios.get("http://localhost:3000/artists");
        this.artists = response.data;
      } catch (error) {
        console.error(error);
      }
    },
  },
};
</script>

Answer №1

When the fetch is triggered, I want to populate the previously empty array "result" with the API response data.

    return {
      result: [],
      searchQuery: "",
    };
  },
fetchArtists() {
      axios
        .get("http://localhost:3000/artists")
        .then((response) => {
          this.result = response.data;
        })
        .catch((error) => {
          console.error(error);
        });
    },

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

Sharing Global Variables in Node.js: What's the Best Way to Pass Them into Required Files?

Recently, I decided to organize my gulpfile.js by splitting it into multiple files within a /gulp folder. However, I encountered an issue when trying to pass a variable debug (boolean) into these files to control the behavior of the gulp command being incl ...

Tips for establishing expiration and validation rules for JSON web tokens

There is an issue with the token expiration time calculation. The comparison of both dates shows that the token would expire in around 17 hours, which is incorrect. It should actually only be 1 minute longer from the time of generation. I would greatly ap ...

Tips for updating images on the second page after clicking on a link from the first page using JavaScript

I need help with a website issue involving two pages. Page 1 features a few images, while page 2 contains another set of images. My goal is to change all the images on page 2 when a specific image on page 1 is clicked. I am able to redirect to page 2 succe ...

Issue with using the bootstrap template plugin for cube portfolio

I have integrated cubeportfolio.js into a bootstrap template, but I am encountering an issue with the custom .js code included in the template that is causing an error in the console. You can view the template I am using here, and it appears to be functio ...

How can I make a jQuery image hover and follow the cursor when hovering over any "a" link?

Hey there! I came across a code snippet on this particular post. What I'm trying to achieve is to have a PNG image display next to the cursor when it hovers over a hyperlink or any "a" link. Here's the original code: var $img = $('img&apos ...

Why does jQuery val() function fail to clear readonly input date in Firefox but succeed in Chrome?

When using JQuery.val(''), I noticed a difference in behavior between Firefox and Chrome. You can see the issue demonstrated in this jsfiddle: https://jsfiddle.net/mdqfbj/d4eovkg8/3/ A JS function triggered by a radio button is supposed to clea ...

Troubleshooting Problem with Scrolling to the Bottom of a DIV Using J

I've been experimenting with creating a chat box in jQuery that automatically scrolls to the bottom when the page loads. I've tried various methods, but most of them haven't worked as expected. One method I found animates a scroll down, but ...

"Counting Down with PHP and jQuery : A Dynamic

I recently received a tutorial on how to combine PHP date function with jQuery. I am looking to modify the script so that when a specific time is reached, it redirects to another page. I attempted to make the changes myself but encountered some issues. Y ...

What is the reason behind this infinite loop occurrence?

As a newcomer to the world of coding, I recently embarked on learning JavaScript. However, I have encountered an issue with a particular piece of code causing an infinite loop that has left me perplexed. Despite having a birthday(myAge) function within t ...

Utilize AJAX response to mark checkbox as checked

I have an HTML checkbox that I am attempting to check using a script received as an ajax response. Below is my HTML snippet: <form class="form-vertical sms-settings-form"> <div class="form-group"> <div data-toggle="tooltip" titl ...

What is the best way to define a function with personalized parameters?

Let me try to explain this the best way I can. Below is a function that generates an HTML element in the #root div: Here is the function: var root = document.getElementById("root"); function createEl(element, selectorType, selectorName, src, in ...

Setting the time based on the length of an SVG shape

Currently, I am delving into the world of JavaScript and React, encountering a challenge where I am required to set time based on the length of an SVG image, similar to a progress bar. To simplify, let's consider a scenario where 24 hours equate to 1 ...

Encountered a problem while executing the VuetifyJS template

I recently completed the installation of a vuetifyjs template by running the command vue init vuetifyjs/webpack-advanced The installation was successful, however, when I attempted to use the npm run dev command, I encountered the following error message: ...

Update a div in PHP using the data received from an AJAX response

I recently developed a PHP application and encountered an issue with updating the value of a date picker. The user is prompted for confirmation when changing the date, and upon confirmation, the date in the "expiry" field (with id expiry) should update alo ...

Loading a unique shape using JSON within the KineticJS framework

Is there a way to load a unique custom shape using a Json file in Kinetic JS? The documentation I found only covers loading normal shapes. ...

Change res without altering the original argument

I'm developing an Express application and I've implemented the AirBnB eslint configuration for linting. The specific lint rule that caught my attention is no-params-reassign, which flags reassignment of function parameters as errors. While I appr ...

Endlessly adding my item to Firebase through the child_added/set feature

Can you assist me in resolving an infinite loop issue I am facing while trying to insert an item into my Firebase through a post form in VueJS? The item keeps getting inserted continuously until I terminate the process. PS : I'm using VueJS ...

The command ESLint create-config is giving me an unrecognized response, both internally and externally

Struggling to integrate ESLint into my latest project despite multiple attempts. Each time I follow the instructions available, I encounter an error stating that create-config does not exist. I've experimented with different versions of ESLint and ev ...

Having trouble interpreting json with angularjs

Looking at the following code snippet, <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Dashboard</title> <!-- Libs --> <script src="angular.js"></script> ...

The server is failing to provide the requested data in JSON format

I am struggling with making a simple API call using Node.js as the backend and React in the frontend. My Node.js file is not returning data in JSON format, and I'm unsure of the reason behind this issue. I need assistance with two main things: Why is ...