|
| 1 | +const baseEndpoint = 'http://www.recipepuppy.com/api'; |
| 2 | +const proxy = `https://cors-anywhere.herokuapp.com/`; |
| 3 | +const form = document.querySelector('form.search'); |
| 4 | +const recipesGrid = document.querySelector('.recipes'); |
| 5 | + |
| 6 | +async function fetchRecipes(query) { |
| 7 | + const res = await fetch(`${proxy}${baseEndpoint}?q=${query}`); |
| 8 | + const data = await res.json(); |
| 9 | + return data; |
| 10 | +} |
| 11 | + |
| 12 | +async function handleSubmit(event) { |
| 13 | + event.preventDefault(); |
| 14 | + const el = event.currentTarget; |
| 15 | + console.log(form.query.value); |
| 16 | + fetchAndDisplay(form.query.value); |
| 17 | +} |
| 18 | + |
| 19 | +async function fetchAndDisplay(query) { |
| 20 | + // turn the form off |
| 21 | + form.submit.disabled = true; |
| 22 | + // submit the search |
| 23 | + const recipes = await fetchRecipes(query); |
| 24 | + console.log(recipes); |
| 25 | + form.submit.disabled = false; |
| 26 | + displayRecipes(recipes.results); |
| 27 | +} |
| 28 | + |
| 29 | +function displayRecipes(recipes) { |
| 30 | + console.log('Creating HTML'); |
| 31 | + const html = recipes.map( |
| 32 | + recipe => `<div class="recipe"> |
| 33 | + <h2>${recipe.title}</h2> |
| 34 | + <p>${recipe.ingredients}</p> |
| 35 | + ${recipe.thumbnail && |
| 36 | + `<img src="${recipe.thumbnail}" alt="${recipe.title}"/>`} |
| 37 | + <a href="${recipe.href}">View Recipe →</a> |
| 38 | + </div>` |
| 39 | + ); |
| 40 | + recipesGrid.innerHTML = html.join(''); |
| 41 | +} |
| 42 | + |
| 43 | +form.addEventListener('submit', handleSubmit); |
| 44 | +// on page load run it with pizza |
| 45 | +fetchAndDisplay('pizza'); |
0 commit comments