El script es una aplicación basada en JavaScript que sirve como interfaz interactiva para manejar y mostrar información de usuarios. Utiliza una API pública y combina datos reales con datos simulados para ofrecer funcionalidades avanzadas de visualización, filtrado y navegación. El propósito de este script es proporcionar una interfaz práctica para visualizar y gestionar datos de usuarios con herramientas modernas. Es útil para aplicaciones donde se necesite interactuar con grandes volúmenes de datos, ofreciendo una experiencia fluida y profesional.
The script is a JavaScript-based application that serves as an interactive interface for managing and displaying user information. It utilizes a public API and combines real data with simulated data to offer advanced features for visualization, filtering, and navigation. The purpose of this script is to provide a practical interface for viewing and managing user data using modern tools. It is useful for applications that require interaction with large volumes of data, delivering a smooth and professional experience.
const y
let para declarar variables y
constantes de manera apropiada, asegurando un
ámbito seguro y evitando problemas con variables
globales.
template literals para construir
dinámicamente el contenido HTML y las cadenas de
texto.
getElementById,
querySelectorAll y
innerHTML.
... como en
la combinación de datos para extender o clonar
arreglos de forma eficiente.
user.address,
user.company).
fetchData,
displayTable, y
showUserProfile.
async/await para
manejar promesas en operaciones asíncronas como
fetch, asegurando un flujo de
trabajo más limpio.
Array.from,
map y filter se
utilizan para manejar colecciones de datos
eficientemente.
const API_URL = 'https://jsonplaceholder.typicode.com/users';
¿Qué hace? Define la URL de la API. Esta URL será utilizada para obtener información de usuarios ficticios desde un servidor.
const ROWS_PER_PAGE = 10;
¿Qué hace? Establece el número de filas que se mostrarán en cada página de la tabla, en este caso 10 filas por página.
let currentPage = 1;
¿Qué hace? Inicializa la variable `currentPage` en 1, indicando que la tabla comenzará mostrando la primera página.
let usersData = [];
¿Qué hace? Crea un arreglo vacío donde se almacenarán los datos de los usuarios obtenidos desde la API o generados localmente.
fetchData())
async function fetchData() {
¿Qué hace? Declara una función asíncrona que se encarga de obtener los datos desde la API y generar datos adicionales.
const resultsContainer = document.getElementById('results');
¿Qué hace? Selecciona el elemento HTML con el id `results` y lo almacena en una variable. Este contenedor se usará para mostrar los datos.
resultsContainer.innerHTML = '<div class="spinner-border" role="status"><span class="visually-hidden">Loading...</span></div>';
¿Qué hace? Muestra un spinner (animación de carga) dentro del contenedor de resultados mientras se obtienen los datos.
const response = await fetch(API_URL);
¿Qué hace? Realiza una solicitud HTTP GET a la URL definida anteriormente (`API_URL`) y espera la respuesta.
if (!response.ok) throw new Error('Error fetching data');
¿Qué hace? Verifica si la solicitud fue exitosa (código de estado HTTP 200). Si no, lanza un error con un mensaje personalizado.
const data = await response.json();
¿Qué hace? Convierte la respuesta de la API en un objeto JSON y lo almacena en la variable `data`.
usersData = [...data, ...generateMockData(40)];
¿Qué hace? Combina los datos
obtenidos de la API con 40 datos ficticios
generados por la función
generateMockData.
currentPage = 1;
¿Qué hace? Reinicia la página actual a la primera página después de cargar los datos.
displayTable();
¿Qué hace? Llama a la función
displayTable() para mostrar los
datos en una tabla con paginación.
} catch (error) { console.error('Error:', error); }
¿Qué hace? Maneja cualquier error que ocurra durante la solicitud y lo registra en la consola del navegador.
generateMockData())
function generateMockData(count) { ... }
¿Qué hace? Genera un arreglo de objetos que simulan usuarios con datos ficticios como nombre, email, dirección, etc.
displayTable())
function displayTable() { ... }
¿Qué hace? Genera
dinámicamente una tabla HTML con los datos
almacenados en usersData,
mostrando solo las filas de la página actual.
const startRow = (currentPage - 1) * ROWS_PER_PAGE;
¿Qué hace? Calcula el índice inicial de los datos que se mostrarán en la página actual.
const pageData = usersData.slice(startRow, endRow);
¿Qué hace? Obtiene un subconjunto de datos para mostrar en la tabla según la página actual.
document.getElementById('prevPage').addEventListener('click', ...);
¿Qué hace? Navega a la página anterior cuando se hace clic en el botón "Previous".
document.getElementById('nextPage').addEventListener('click', ...);
¿Qué hace? Navega a la página siguiente cuando se hace clic en el botón "Next".
const and
let to declare variables and
constants appropriately, ensuring safe scoping
and avoiding issues with global variables.
template literals to dynamically
construct HTML content and text strings.
getElementById,
querySelectorAll, and content is
updated with innerHTML.
... operators are used to
efficiently extend or clone arrays, such as
combining data.
user.address,
user.company).
fetchData,
displayTable, and
showUserProfile.
async/await to
handle promises in asynchronous operations
like fetch, ensuring a cleaner
workflow.
Array.from,
map, and filter are
used to efficiently handle data collections.
const API_URL = 'https://jsonplaceholder.typicode.com/users';
What it does: Defines the API URL from which user data will be fetched.
const ROWS_PER_PAGE = 10;
What it does: Sets the number of rows (users) displayed per page in the table, in this case, 10 rows per page.
let currentPage = 1;
What it does: Initializes the `currentPage` variable to 1, indicating the table starts on the first page.
let usersData = [];
What it does: Creates an empty array where user data fetched from the API or generated locally will be stored.
fetchData())
async function fetchData() {
What it does: Declares an asynchronous function responsible for fetching data from the API and generating additional mock data.
const resultsContainer = document.getElementById('results');
What it does: Selects the HTML element with the ID `results` and stores it in a variable. This container will display the fetched data.
resultsContainer.innerHTML = '<div class="spinner-border" role="status"><span class="visually-hidden">Loading...</span></div>';
What it does: Displays a spinner (loading animation) in the results container while the data is being fetched.
const response = await fetch(API_URL);
What it does: Makes an HTTP GET request to the API URL and waits for the response.
if (!response.ok) throw new Error('Error fetching data');
What it does: Checks if the request was successful (HTTP status code 200). If not, it throws an error with a custom message.
const data = await response.json();
What it does: Converts the API response to JSON format and stores it in the `data` variable.
usersData = [...data, ...generateMockData(40)];
What it does: Combines the
fetched data with 40 mock user records generated
by the generateMockData function.
currentPage = 1;
What it does: Resets the current page to the first page after loading the data.
displayTable();
What it does: Calls the
displayTable() function to display
the data in a table with pagination.
} catch (error) { console.error('Error:', error); }
What it does: Handles any errors during the request and logs them in the browser console.
generateMockData())
function generateMockData(count) { ... }
What it does: Generates an array of objects simulating user records with mock data such as name, email, address, etc.
displayTable())
function displayTable() { ... }
What it does: Dynamically
generates an HTML table with data stored in
usersData, displaying only the rows
for the current page.
const startRow = (currentPage - 1) * ROWS_PER_PAGE;
What it does: Calculates the starting index of the data to be displayed for the current page.
const pageData = usersData.slice(startRow, endRow);
What it does: Extracts a subset of the data to display on the current page.
document.getElementById('prevPage').addEventListener('click', ...);
What it does: Navigates to the previous page when the "Previous" button is clicked.
document.getElementById('nextPage').addEventListener('click', ...);
What it does: Navigates to the next page when the "Next" button is clicked.