Loader
Loader is about using the CSS that is provided to you. We copy and paste the html into our js file. Since the style file is present, it will animate the loader.
We then call the renderLoader js function in the controller.
src/js/views/base.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
export const renderLoader = parent => { const loader = ` <div class="loader"> <svg> <use href="img/icons.svg#icon-cw"></use> </svg> </div> `; parent.insertAdjacentHTML('afterbegin', loader); } export const clearLoader = () => { const loader = document.querySelector('.loader') if (loader) { loader.parentElement.removeChild(loader); } } |
When the data fetched is finished, we then call the removeLoader. We basically find the element with the class name ‘.loader’ and then go up to its parent, and call removeChild on it.
src/js/index.js
Now just use them right before and after the fetching of your data result.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
const controlSearch = async () => { const query = searchView.getInput(); if (query) { state.search = new Search(query); searchView.clearInput(); searchView.clearResults(); renderLoader(elements.searchRes) await state.search.getResults() clearLoader() searchView.renderResults(state.search.result) } } |
Pagination
Pagination is part of rendering the results that we fetched from the backend.
src/js/index.js
1 2 3 4 5 6 7 |
const controlSearch = async () => { const query = searchView.getInput(); if (query) { ... searchView.renderResults(state.search.result) } } |
We need to modify our renderResults functionality. Before, we just a simple forEach that renders all results. Now we have to be more selective.
We need to know two things, the page we’re on and the number of results per page.
We calculate for start and end so that we can selectively extract those data to be displayed.
If we were to start on say page 1, and 10 results per page we need 0-9.
if we start on page 2, 10 – 19…
…etc.
for ‘start’, we just do: (page-1) * resPerPage
for ‘end’, we simply do: page * resPerPage
Notice we get 0, 10
10 – 20
20 – 30…
We then use slice to get the start/end – 1
so slice(0,10) means to get elements from index 0 to 9
slice (10, 20) means to get elements from index 10 to 19
…etc
which is exactly how we want to render our recipes.
src/js/views/searchView.js
1 2 3 4 5 6 7 |
export const renderResults = (recipes, page=1, resPerPage=10) => { const start = (page - 1) * resPerPage; const end = page * resPerPage; recipes.slice(start, end).forEach(recipe => renderRecipe(recipe)) renderButtons(page, recipes.length, resPerPage) } |