简体   繁体   中英

is there a way I can add images and strings to an array and store on local storage and display them using JavaScript?

Am building an a recipe app that displays images of foods and their respective names from spoonicular api. So when a user sees a food they like they click the like icon which in turn will add the food to a favorite section on top. The logic is that the image url and name of food will be stored on local storage and then displayed in the favorite section. However I have the following problems 1.i cannot seem to be able to display the image and and and name despite successfully storing them on local storage 2.The like icon which becomes active when clicked only works for the first food item below is my code

  document.getElementById("search").addEventListener("click",()=>{
const input=document.getElementById("input")
input.style.display="block"
input.style.border="solid"
})

 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,
      servings,
      image,
      dishTypes,
      instructions,
    } = recipe;
    console.log(recipe)
      data1+=`  
      <div class="meal-header">
          <img src=${recipe.image} alt=${recipe.title} >
      </div>
      <div class="meal-body">
          <h5>${recipe.title}</h5>
          <button class="fav-btn">
              <i class="fa fa-heart"></i>
          </button>
      </div>`
      const meal=document.querySelector(".meal")
      meal.innerHTML=data1
      const favBtn=meal.querySelector(".fav-btn i")
      favBtn.addEventListener("click",()=>{
          favBtn.classList.add("active")
          let array1=[recipe.image,recipe.title]
          myFavMeals.push(...array1)
          console.log(myFavMeals)
          localStorage.setItem("myFavMeals",JSON.stringify(myFavMeals))
         showMeal()
      })
})

 }).catch((err)=>{
  console.log(err)
 })
  }
getRandomMeal()


   function getMealBySearch(){
  document.querySelector('#input').addEventListener('keypress', function (e) {
if (e.key === 'Enter') { 
  const term=document.getElementById("input").value
  fetch(`https://api.spoonacular.com/recipes/complexSearch? 
  query=${term}&number=10&apiKey=b354ffb530c5444da1eec4b02a3146be`).then((data)=>{
    console.log(data) 
  return data.json()
    
}).then((completedata)=>{
  console.log(completedata)
  console.log(completedata.results)
let data3=""
completedata.results.forEach((recipe) => {
  const {
    id,
    title,
    readyInMinutes,
    servings,
    image,
    dishTypes,
    instructions,
  } = recipe;
    data3+=`
    <div class="meal-header">
        <img src=${recipe.image} alt=${recipe.title}>
    </div>
    <div class="meal-body">
        <h5>${recipe.title}</h5>
        <button class="fav-btn">
            <i class="fa fa-heart"></i>
        </button>
    </div>`
      
    const favBtn=document.querySelector(".fav-btn i")
    favBtn.addEventListener("click",()=>{
        favBtn.classList.toggle("active")
        let array1=[recipe.image,recipe.title]
        myFavMeals.push(...array1)
        console.log(myFavMeals)
        localStorage.setItem("myFavMeals",JSON.stringify(myFavMeals))
       showMeal()
 
    
   })
     
})
const meal=document.querySelector(".meal")
      meal.innerHTML=data3
     

}).catch((err)=>{
  console.log(err)
  })
   }
  });

 }
 getMealBySearch()
 

    function showMeal(){
       let favmeal= JSON.parse(localStorage.getItem(myFavMeals)) 
        renderFavMeal()
      
        function renderFavMeal(){
          meallist=""
          favmeal.forEach((meal) => {
            const {
              image,
              name
            } = meal;
              meallist+=`<ul>
              <li><img src=${meal.image} alt=${meal.name}><span>${meal.name}</span></li>
          </ul>`
          })
          document.querySelector(".fav-meals").innerHTML=meallist
        }
      }
  
    
      

When retrieving data from local storage you need to use the key (DOMstring) you saved it as.

let favmeal= JSON.parse(localStorage.getItem(myFavMeals))

This way you are trying to retrieve the array you set in the code above. Put it in quotes to make it a key:

let favmeal= JSON.parse(localStorage.getItem("myFavMeals"))

You should be asking separate question for these. But the icon becomes active because you are selecting only the first one.

const favBtn=meal.querySelector(".fav-btn i")

This selector selects only the first element that matches the query.

Insead you should use querySelectorAll() and loop through the nodelist

const favBtns = meal.querySelectorAll(".fav-btn i")

favBtns.forEach(favBtn => {
  favBtn.addEventListener("click",() => {
       ...
      })
})
  

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM