82 lines
2.3 KiB
JavaScript
82 lines
2.3 KiB
JavaScript
//this class returns a list of cards to the DOM
|
|
//by mapping (looping) over an array
|
|
|
|
import IdeasApi from '../services/ideasApi';
|
|
|
|
class IdeaList {
|
|
constructor() {
|
|
this._ideaListEl = document.querySelector('#idea-list');
|
|
this._ideas = [];
|
|
this._getIdeas();
|
|
|
|
//adding a set (datatype)
|
|
this._validTags = new Set();
|
|
this._validTags.add('technology');
|
|
this._validTags.add('software');
|
|
this._validTags.add('business');
|
|
this._validTags.add('education');
|
|
this._validTags.add('health');
|
|
this._validTags.add('inventions');
|
|
}
|
|
|
|
async _getIdeas() {
|
|
try {
|
|
const res = await IdeasApi.getIdeas();
|
|
this._ideas = res.data.data_base; //in axios, when you make a request the info comes wrapped in an object called data,
|
|
//data refers to the axios object and data_base refers to the info being returned from the backend
|
|
this.render();
|
|
// console.log(this._ideas);
|
|
} catch (error) {
|
|
console.log(error);
|
|
}
|
|
}
|
|
|
|
addIdeaToList(idea) {
|
|
this._ideas.push(idea);
|
|
this.render();
|
|
}
|
|
|
|
getTagClass(tag) {
|
|
tag = tag.toLowerCase();
|
|
let tagClass = '';
|
|
//check if the tag that is passed in is within the set
|
|
if (this._validTags.has(tag)) {
|
|
tagClass = `tag-${tag}`;
|
|
} else {
|
|
tagClass = '';
|
|
}
|
|
return tagClass;
|
|
}
|
|
|
|
render() {
|
|
//use map on the array, creating a card for each item in the array and display
|
|
// them on the DOM
|
|
//map takes in a function as a parameter
|
|
|
|
this._ideaListEl.innerHTML = this._ideas
|
|
.map((idea) => {
|
|
//passing the tag entered for each item into the getTagClass function on each iteration of the map
|
|
const tagClass = this.getTagClass(idea.tag);
|
|
//it will be treated as an array of template strings
|
|
return `
|
|
|
|
<div class="card">
|
|
<button class="delete"><i class="fas fa-times"></i></button>
|
|
<h3>
|
|
${idea.text}
|
|
</h3>
|
|
<p class="tag ${tagClass}">${idea.tag.toUpperCase()}</p>
|
|
<p>
|
|
Posted on <span class="date">${idea.date}</span> by
|
|
<span class="author">${idea.username}</span>
|
|
</p>
|
|
</div>
|
|
|
|
`;
|
|
})
|
|
.join(''); //to turn it back in to a string
|
|
}
|
|
}
|
|
|
|
export default IdeaList;
|