Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f83cca1

Browse files
Adding fetch
1 parent 0349d0c commit f83cca1

File tree

3 files changed

+55
-23
lines changed

3 files changed

+55
-23
lines changed

‎app/js/script.js

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -48,12 +48,15 @@ const removeAllChild = (parent) => {
4848
let pageIndex = 1;
4949
let searchValue;
5050

51+
52+
// Creamos una función que nos permita realizar el fetch a partir de una URL y retornar la 'data' para asi trabajarla como querramos.
5153
const fetchPhotos = async (baseURL) => {
5254
const res = await fetch(baseURL, HEADERS);
5355
const data = await res.json();
5456
return data;
5557
}
5658

59+
// Creamos una función que valide lo ingresado por el usuario.
5760
const validateSearchValue = (searchValue) => {
5861
if (searchValue.length < 3){
5962
// Avisamos el error.
@@ -67,13 +70,15 @@ const validateSearchValue = (searchValue) => {
6770
}
6871
}
6972

73+
// Creamos una función que nos permita mapear las fotos devueltas por la API, crear una instancia del objeto Photo a partir de los datos de la API, y crear su respectivo elemento en HTML.
7074
const generateHTML = (data, photoType) => {
7175
data.photos.forEach((photoObject) => {
7276
const photo = new Photo(photoObject);
7377
// Creamos un nuevo elemento article.
7478
let newGalleryItem = document.createElement('article');
7579
// Le asignamos la clase que define los estilos que poseerán las fotos.
7680
newGalleryItem.classList.add('gallery__item');
81+
// Le asignamos un atributo 'data-photo' para poder saber si la foto es el resultado de una búsqueda o es una foto random.
7782
newGalleryItem.setAttribute('data-photo', photoType);
7883
// Y le ponemos una etiqueta img con los datos del objeto para que se muestren.
7984
newGalleryItem.innerHTML = `<img src="${photo.src.large}" alt="${photo.alt}"></img>`;
@@ -82,25 +87,36 @@ const generateHTML = (data, photoType) => {
8287
});
8388
}
8489

90+
// Creamos una función que nos permita validar algunos errores para asi mostrarlos por el HTML.
91+
const validateErrors = (data, searchValue) => {
92+
// Si no tiene más paginaciones, oculta el botoón de cargar más fotos.
93+
if (!data.next_page){
94+
loadMoreBtn.style.display = 'none'
95+
}
96+
// Si la API nos devuelve una array vacio, por medio de un H2 informamos el error.
97+
if (data.photos.length === 0){
98+
let textError = document.createElement('h2');
99+
textError.innerText = `No se encontraron fotos de '${searchValue}'`;
100+
gallery.prepend(textError);
101+
}
102+
}
103+
85104
// Creamos una función que nos devuelva las fotos a partir de lo ingresado por el usuario en la barra de búsqueda.
86105
const getSearchedPhotos = async (e) => {
87106
e.preventDefault();
88107
searchValue = e.target.querySelector('input').value;
89108
if (validateSearchValue(searchValue) === true){
90109
const data = await fetchPhotos(`https://api.pexels.com/v1/search?query=${searchValue}&per_page=16`);
91-
if (!data.next_page){
92-
loadMoreBtn.style.display = 'none'
93-
}
110+
validateErrors(data, searchValue);
94111
removeAllChild(galleryContainer);
95112
generateHTML(data, 'search');
96113
}
97114
}
98115

116+
// Creamos una función que nos devuelva otras páginas de fotos respecto de la búsqueda anterior.
99117
const getMoreSearchedPhotos = async (index) => {
100118
const data = await fetchPhotos(`https://api.pexels.com/v1/search?query=${searchValue}&per_page=16&page=${index}`);
101-
if (!data.next_page){
102-
loadMoreBtn.style.display = 'none'
103-
}
119+
validateErrors(data, searchValue);
104120
generateHTML(data, 'search');
105121
}
106122

@@ -113,6 +129,7 @@ const getInitialRandomPhotos = async (index) => {
113129
generateHTML(data, 'curated');
114130
}
115131

132+
// Creamos una funcióm que nos permita cargar las paginaciones dependiendo del tipo de foto.
116133
const loadMorePhotos = () => {
117134
let index = ++pageIndex;
118135
let galleryItem = document.querySelector('article');
@@ -129,6 +146,7 @@ const loadMorePhotos = () => {
129146

130147
// Evento submit del form, donde se llama a una función que trae las fotos a partir de la búsqueda.
131148
searchForm.addEventListener('submit', (e) => getSearchedPhotos(e));
149+
// Evento click del botón para cargar más fotos mediante las paginaciones de la API.
132150
loadMoreBtn.addEventListener('click', () => loadMorePhotos());
133151
// Cuando se carge la ventana, llamamos a la función que nos carga 8 fotos simulando que son fotos aleatorias.
134152
document.addEventListener('DOMContentLoaded', getInitialRandomPhotos(pageIndex));
@@ -139,19 +157,17 @@ clearInputButton.addEventListener('click', () => {
139157
// Limpiamos el input.
140158
document.getElementById('searchInput').value = '';
141159
// Cuando la galería tiene 3 hijos es porque no se tuvo que crear el h2 para error. Sino, si se tuvo que crear el h2 por lo que tiene más hijos.
142-
/* if (gallery.childNodes.length == 3){
160+
if (gallery.childNodes.length === 3){
143161
// Borra los hijos del contenedor de la galería.
144162
removeAllChild(galleryContainer);
145163
// Carga las fotos aleatorias del principio.
146164
getInitialRandomPhotos(pageIndex);
147165
}else{
148166
// Borra el h2 con el error.
149-
gallery.childNodes[1].remove();
167+
gallery.childNodes[0].remove();
150168
// Carga las fotos aleatorias del principio.
151169
getInitialRandomPhotos(pageIndex);
152-
} */
153-
removeAllChild(galleryContainer);
154-
getInitialRandomPhotos(pageIndex);
170+
}
155171
loadMoreBtn.style.display = 'flex';
156172
});
157173

‎dist/script.js

Lines changed: 27 additions & 11 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /