@@ -48,12 +48,15 @@ const removeAllChild = (parent) => {
48
48
let pageIndex = 1 ;
49
49
let searchValue ;
50
50
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.
51
53
const fetchPhotos = async ( baseURL ) => {
52
54
const res = await fetch ( baseURL , HEADERS ) ;
53
55
const data = await res . json ( ) ;
54
56
return data ;
55
57
}
56
58
59
+ // Creamos una función que valide lo ingresado por el usuario.
57
60
const validateSearchValue = ( searchValue ) => {
58
61
if ( searchValue . length < 3 ) {
59
62
// Avisamos el error.
@@ -67,13 +70,15 @@ const validateSearchValue = (searchValue) => {
67
70
}
68
71
}
69
72
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.
70
74
const generateHTML = ( data , photoType ) => {
71
75
data . photos . forEach ( ( photoObject ) => {
72
76
const photo = new Photo ( photoObject ) ;
73
77
// Creamos un nuevo elemento article.
74
78
let newGalleryItem = document . createElement ( 'article' ) ;
75
79
// Le asignamos la clase que define los estilos que poseerán las fotos.
76
80
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.
77
82
newGalleryItem . setAttribute ( 'data-photo' , photoType ) ;
78
83
// Y le ponemos una etiqueta img con los datos del objeto para que se muestren.
79
84
newGalleryItem . innerHTML = `<img src="${ photo . src . large } " alt="${ photo . alt } "></img>` ;
@@ -82,25 +87,36 @@ const generateHTML = (data, photoType) => {
82
87
} ) ;
83
88
}
84
89
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
+
85
104
// Creamos una función que nos devuelva las fotos a partir de lo ingresado por el usuario en la barra de búsqueda.
86
105
const getSearchedPhotos = async ( e ) => {
87
106
e . preventDefault ( ) ;
88
107
searchValue = e . target . querySelector ( 'input' ) . value ;
89
108
if ( validateSearchValue ( searchValue ) === true ) {
90
109
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 ) ;
94
111
removeAllChild ( galleryContainer ) ;
95
112
generateHTML ( data , 'search' ) ;
96
113
}
97
114
}
98
115
116
+ // Creamos una función que nos devuelva otras páginas de fotos respecto de la búsqueda anterior.
99
117
const getMoreSearchedPhotos = async ( index ) => {
100
118
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 ) ;
104
120
generateHTML ( data , 'search' ) ;
105
121
}
106
122
@@ -113,6 +129,7 @@ const getInitialRandomPhotos = async (index) => {
113
129
generateHTML ( data , 'curated' ) ;
114
130
}
115
131
132
+ // Creamos una funcióm que nos permita cargar las paginaciones dependiendo del tipo de foto.
116
133
const loadMorePhotos = ( ) => {
117
134
let index = ++ pageIndex ;
118
135
let galleryItem = document . querySelector ( 'article' ) ;
@@ -129,6 +146,7 @@ const loadMorePhotos = () => {
129
146
130
147
// Evento submit del form, donde se llama a una función que trae las fotos a partir de la búsqueda.
131
148
searchForm . addEventListener ( 'submit' , ( e ) => getSearchedPhotos ( e ) ) ;
149
+ // Evento click del botón para cargar más fotos mediante las paginaciones de la API.
132
150
loadMoreBtn . addEventListener ( 'click' , ( ) => loadMorePhotos ( ) ) ;
133
151
// Cuando se carge la ventana, llamamos a la función que nos carga 8 fotos simulando que son fotos aleatorias.
134
152
document . addEventListener ( 'DOMContentLoaded' , getInitialRandomPhotos ( pageIndex ) ) ;
@@ -139,19 +157,17 @@ clearInputButton.addEventListener('click', () => {
139
157
// Limpiamos el input.
140
158
document . getElementById ( 'searchInput' ) . value = '' ;
141
159
// 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 ) {
143
161
// Borra los hijos del contenedor de la galería.
144
162
removeAllChild ( galleryContainer ) ;
145
163
// Carga las fotos aleatorias del principio.
146
164
getInitialRandomPhotos ( pageIndex ) ;
147
165
} else {
148
166
// Borra el h2 con el error.
149
- gallery.childNodes[1 ].remove();
167
+ gallery . childNodes [ 0 ] . remove ( ) ;
150
168
// Carga las fotos aleatorias del principio.
151
169
getInitialRandomPhotos ( pageIndex ) ;
152
- } */
153
- removeAllChild ( galleryContainer ) ;
154
- getInitialRandomPhotos ( pageIndex ) ;
170
+ }
155
171
loadMoreBtn . style . display = 'flex' ;
156
172
} ) ;
157
173
0 commit comments