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?
- How do I show data when the page loads?
- 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>