34. Places - Favorite Places

Explore cool, quirky places in your own backyard.

Loading...

HTML

1
2
<p>Explore cool, quirky places in your own backyard.</p>
<div id="app">Loading...</div>

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/* For each place, add a “favorite” button. Give the button a different appearance
when the place is “favorited” versus when it’s not. When the user revisits the page,
their favorites should reload. You do not need to filter
or show only the favorite anywhere (that’s a future project). */

const favesID = "favoritePlace";
const app = new Reef('#app', {
data: {},
template: function (props) {
if (props.posts && props.posts.length) {
let html = '<div class="container">' + props.posts.map(function (post) {
return `<div class="post-container"><div class="miniature-container"><img class="minature" src="${post.img}" /></div><div class="info-container"><div class="header"><h2 class="title">${post.place}</h2><button data-fave="${post.id}" class="fave-btn" aria-label="add ${post.place} to favorite" aria-pressed="${props.faves[post.id]}" title="Add to favorite!">&#x2665;</button></div><p>${post.description}</p><p><em>${post.location}</em></p><a href=${post.url} target="_blank">Read more</a></div></div>`;
}).join('') + '</div>';
return html;
}
let html = '<p>Unable to find any places right now.</p>'
return html;
}
});
const getFaves = function () {
const faves = localStorage.getItem(favesID);
const favesObj = faves ? JSON.parse(faves) : {};
return favesObj;
}
const saveFaves = function (faves) {
localStorage.setItem(favesID, JSON.stringify(faves));
}
const getPosts = function () {
fetch('https://vanillajsacademy.com/api/places.json').then(function (response) {
if (response.ok) {
return response.json();
}
return Promise.reject(response);
}).then(function (data) {
app.data.faves = getFaves();
app.data.posts = data;
}).catch(function (error) {
console.warn(error);
app.data.posts = null;
})
}
const clickHandler = function (e) {
const postPlace = e.target.getAttribute('data-fave');
if (!postPlace) return;
console.log(postPlace);
app.data.faves[postPlace] = app.data.faves[postPlace] ? false : true;
saveFaves(app.data.faves);
}
getPosts();
document.addEventListener('click', clickHandler);