Skip to main content

Forkify - Vanilla JS

282. Loading a Recipe from API


async/fetch

const showRecipe = async function () {
  try {
    renderSpinner(recipeContainer);
    // 1) Loading recipe
    const res = await fetch(
      'https://forkify-api.herokuapp.com/api/v2/recipes/5ed6604591c37cdc054bc886'
    );



283. Rendering the recipe 

after making markup html code 

    recipeContainer.innerHTML = '';

    recipeContainer.insertAdjacentHTML('afterbegin'markup);



284. Listening for load and hashchange events

dynamic id after removing '#' with slice(1)

    const id = window.location.hash.slice(1);

    renderSpinner(recipeContainer);
    // 1) Loading recipe
    const res = await fetch(
      `https://forkify-api.herokuapp.com/api/v2/recipes/${id}`
    );

ev will change hash and then will be loaded 

['hashchange''load'].forEach(ev => window.addEventListener(evshowRecipe));


285. The MVC architecture 


286. Refactoring for MVC

1- refactoring to handle state in model

await model.loadRecipe(id); // loadRecipe is async () so need await
    const { recipe } = model.state;

loadReciple() is async function so needs wait 

and by destructing {recipe}, can keep the code


2.  markup and renderSpinner

// 2) Rendering recipe
    recipeView.render(model.state.recipe);

in controller, (model.state.recipe) pass with render 

in View, so that recipe,in controller, refers this.#data

  render(data) {
    this.#data = data;
  }

add babelrc to use private variable 

[mistake] this.#generateMarkup() & img source path 


3. fractional to handle number thing

              ing.quantity ? new Fraction(ing.quantity).toString() : ''

and replace ingrdient to ing 


287. Helpers and Configuration

config.js for allowing us to configure by changing some of the data like API_URL

helpers.js is to contain a couple of function that we reuse like getJSON()

in Model.js 

    const data = await getJSON(`${API_URL}/${id}`);

in helpers.js

we need to return data so (this data) will become the resolved value of this promise

    return data;


error handling

we want to handle the error in model.js. So, we have to re-throw the error


promise.race() will decide to resolve or reject and if timeout_sec pass, then error show up


288. Event Handlers in MVC: publisher and subscriber pattern 

  recipeView.addHandlerRender(controlRecipes);
Events should be handled in the controller
Events should be listened for in the view 
solution : Subscribe to publisher by passing in the subscriber function
=> controlRecipes will be passed into addHandlerRender when problem starts
Controller is subscriber & view is publisher.

controller(controlRecipes) pass to view in addHandelerRender()

controller 

const init = function () {
  recipeView.addHandlerRender(controlRecipes);
};

views, passing controlRecipes() function as handler

  addHandlerRender(handler) {
    ['hashchange''load'].forEach(ev => window.addEventListener(evhandler));
  }


289. Implementing Error and Success Messages 

throw err in model and then

in controller 

recipeView.renderError(); // to display error in view


create renderError()  and renderMessage() to handle that msg function



290. Implementing search Part 1 

export const loadSearchResults = async function (query) {
  try {
    const data = await getJSON(`${API_URL}?search=${query}`);
    console.log(data);
  } catch (err) {
    console.log(`${err}`);
    throw err;
  }
};

loadSearchResults('pizza');


load search results

store all recipes search data into state

control handles the search result 

Let search component works 


291. Implementing search Part 2

after chaning from #private to _protected, 

extracting common View code from recepiceView,

Displaying renderringSpinner without writing a new code

where is the search result data?

    // 3) Render results
    resultsView.render(model.state.search.results);

in the View.js render()

  render(data) {
    this._data = data;


render all search results

check query 

    if (!data || (Array.isArray(data&& data.length === 0))
      return this.renderError();


292. Implementing pagination Part 1 

from model

export const getSearchResultsPage = function (page = state.search.page) {
  state.search.page = page;

  const start = (page - 1* state.search.resultPerPage//0
  const end = page * state.search.resultPerPage//9

  return state.search.results.slice(startend);
};

Set start and end like 0 -10 

in controller

    resultsView.render(model.getSearchResultsPage());

& set page state


293. Implementing pagination Part 2

compute how many pages we get 

figure out the page num

add button for each scinarios

click on button

use that number to render the results 

Mistake

 'const goToPage = +btn.dataset.goto'

+ sign convert to number type 


294. Project Planning II

4. Change servings functionality 

5. Bookmarking funcitonality

6. Store bookmark data in the browser

7. On page load, read saved bookmarks 


295. Updating recipe servings

update entire view with the new state

to connect with the UI, use data-sth 

      const { updateTo } = +btn.dataset;
      handler(updateTo);

updating the serving number with updateTo


296. Developing a DOM updating algorithm



297. Implementing Bookmark - Part 1



298. Implementing Bookmark - Part 2



299. Storing bookmarks with localStorage



300. Project planning III



301. Uploading a new Recipe - Part 1



302. Uploading a new Recipe - Part 2



303. Uploading a new Recipe - Part 3



304. Final wrapping up




Comments

Popular posts from this blog

[BAEKJOON Online Judge + Node.js] 2292: Honeycomb

  I did't use while loop that much so didn't come up what to do. While loop create a loop that execute a specific statement. So, the main point of this problem is "prevNum + max * 6" input = 13, output = 3 https://www.acmicpc.net/problem/2292 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while const input = require ( "fs" ). readFileSync ( "/dev/stdin" ). toString () ; let count = 1 ; let max = 1 ; // set the range while (max < input) { max += count * 6 ; count ++ ; } console . log (count) ; // prevNum + count * 6 // 1 so +6 every loop! // 2 - 7, 5 // 8 - 19, 11 // 20 - 37, 17 // 38 - 61, 23

FE WebDev Routine Training Feb 09, 2021

 FE WebDev Routine Training Feb 09, 2021  A lot of things to do. DO FUCKING FOCUS!!!  Coding test - codewar 1 Kakao 2021 No.1 CSS - grid/ SCSS and Cloning(besthorrorscenes.com) JS - for of loop/  Sec9/ DOM array methods toy project React -   A bit of Yelp Portfolio -  List the 100JS projects Job hunting -  NAVER Finance(on 10th) Karrot for  internship  Apply SW maestro