decouple-1.0.x-dev/example/fetchData.js
example/fetchData.js
/*
* Script Name: Fetch data
* Description: Fetches data from a URL specified in the 'data-url' attribute
* of the container element and displays it on the page.
*/
// Select the element with the ID 'data-container'.
const container = document.getElementById('data-container');
// Get the value of the 'data-url' attribute from the selected element.
// Use this URL to fetch data dynamically.
const dataUrl = container.getAttribute('data-url');
// Fetch data from the URL
fetch(dataUrl)
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then((data) => {
displayProducts(data.products); // Process the products array.
})
.catch((error) => {
container.textContent = 'Failed to load data.';
});
// Function to display data in the container
function displayProducts(products) {
products.forEach((product) => {
const element = document.createElement('p');
element.textContent = `Product: ${product.name}, Price: $${product.price}, In stock: ${product.in_stock}, Rate: ${product.rating}`;
container.appendChild(element);
});
}
