dabidabidesh

cookbook

Mar 1st, 2021
777
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const getRecipesList = async () => {
  2.   try {
  3.     const response = await fetch('http://localhost:3030/jsonstore/cookbook/recipes');
  4.     const main = document.querySelector('main');
  5.     if (response.ok == false) {
  6.       throw new Error(response.statusText);
  7.     }
  8.     const recipes = await response.json();
  9.     main.querySelector('p').remove();
  10.     Object.values(recipes)
  11.       .map(createPreview)
  12.       .forEach(r => main.appendChild(r));
  13.   } catch (err) {
  14.     alert(err.message);
  15.   }
  16. };
  17.  
  18. const getRecipeDetails = async (id, preview) => {
  19.  
  20.   const response = await fetch('http://localhost:3030/jsonstore/cookbook/details/' + id);
  21.   const recipe = await response.json();
  22.  
  23.   const result = `
  24.   <h2>${recipe.name}</h2>
  25.     <div class="band">
  26.       <div class="thumb">
  27.         <img src="${recipe.img}">
  28.                 </div>
  29.         <div class="ingredients">
  30.           <h3>Ingredients:</h3>
  31.           <ul>
  32.           ${recipe.ingredients.map(i => `<li>${i}</li>`).join('')}
  33.           </ul>
  34.         </div>
  35.       </div>
  36.       <div class="description">
  37.         <h3>Preparation:</h3>
  38.         ${recipe.steps.map(s => `<p>${s}</p>`).join('')}
  39.       </div>
  40.   `;
  41.  
  42.   const articleElement = document.createElement('article');
  43.   articleElement.insertAdjacentHTML('beforeend', result);
  44.   articleElement.querySelector('h2').onclick = () => toggleR();
  45.  
  46.   preview.replaceWith(articleElement);
  47.  
  48.   function toggleR() {
  49.     articleElement.replaceWith(preview);
  50.   }
  51. }
  52. const createPreview = (recipe) => {
  53.  
  54.   const result = `
  55.     <div class="title">
  56.       <h2>${recipe.name}</h2>
  57.     </div>
  58.     <div class="small">
  59.       <img src="${recipe.img}">
  60.     </div>`;
  61.  
  62.   const articleElement = document.createElement('article');
  63.   articleElement.classList.add('preview');
  64.   articleElement.insertAdjacentHTML('beforeend', result);
  65.  
  66.   articleElement.onclick = () => getRecipeDetails(recipe._id, articleElement);
  67.  
  68.   return articleElement;
  69. }
  70.  
  71. window.onload = () => {
  72.   console.log('before request');
  73.   getRecipesList();
  74.   console.log('after request');
  75. };
RAW Paste Data