The code below fetches images and their names from a food api. I am able to store to those images in the local storage once a user hits the like button.i however want to get back the stored image and name data and display them in a favorite tab. But I can't seem to be able to achieve that..Any help?
let myFavMeals=[]
function getRandomMeal(){
fetch('https://api.spoonacular.com/recipes/random?
number=10&apiKey=b354ffb530c5444da1eec4b02a3146be').then((data)=>{
console.log(data)
return data.json()
}).then((completedata)=>{
console.log(completedata.recipes)
let data1=""
completedata.recipes.forEach((recipe) => {
const {
id,
title,
readyInMinutes,
extendedIngredients,
servings,
image,
dishTypes,
instructions,
} = recipe;
data1+=`
<div class="meal-header">
<img src=${recipe.image} alt=${recipe.title} >
</div>
<div class="meal-body">
<h6>${recipe.title}</h6>
<p class="show">see recipes</p>
<button class="fav-btn">
<i class="fa fa-heart"></i>
</button>
</div>
<div class="holder">
<div class="meal-desc">
<p>ready in : ${recipe.readyInMinutes} minutes</p>
<center><h6>instructions</h6></center>
<p>${recipe.instructions} </p>
</div>
</div>`
})
const meal=document.querySelector(".meal")
meal.innerHTML=data1
const holder=document.querySelector(".holder")
const show=document.querySelectorAll(".show")
show.forEach(shows=>{
showcounter=0
shows.addEventListener("click",()=>{
holder.style.display="block"
showcounter++
if(showcounter== 2) {
holder.style.display="none"
}
})
})
const favBtns=meal.querySelectorAll(".fav-btn i")
const images = document.querySelectorAll('.meal-header > img')
favBtns.forEach((favBtn,i)=>{
favBtn.addEventListener("click", ()=>{
favBtn.classList.add("active")
console.log(images[i].src, images[i].alt)
myFavMeals.push(images[i].src, images[i].alt)
localStorage.setItem("myFavMeals", JSON.stringify(myFavMeals))
showMeal()
})
})
}).catch((err)=>{
console.log(err)
})
}
getRandomMeal()
function showMeal(){
let favmeal= JSON.parse(localStorage.getItem("myFavMeals"))
favmeal.forEach(favmeals=>{
let meallist=""
meallist+=`<ul>
<li><img src=${favmeal} alt=${favmeal[i].alt}><span>${favmeal[i].alt}</span></li>
</ul>`
document.querySelector(".fav-meals").innerHTML+=meallist
})
}
You can save the favorites in the array as objects using object literal:
myFavMeals.push({src: images[i].src, alt: images[i].alt})
And then access them in the loop using the keys src
and alt
:
function showMeal() {
let favmeal = JSON.parse(localStorage.getItem("myFavMeals"));
favmeal.forEach(favmeal => {
let meallist = "";
meallist += `<ul>
<li><img src=${favmeal.src} alt=${favmeal.alt}><span>${favmeal.alt}</span></li>
</ul>`;
document.querySelector(".fav-meals").innerHTML += meallist;
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.