I'm making a simple webshop, where the products comes from a JSON file. I use Fetch API to gain access to the JSON file and insert it into the HTML. This works fine.
I also want to save all the products in an array so I can have access to them without having to fetch them again.
But accessing the array outside the fetch either outputs "undefined" or an array where I can't access the array items. Depending on how I try to fill the array.
In this case I try to push each array item (which are objects) into the productsArray in the forEach loop. But trying to access the array items with productsArray[0] for example outputs undefined.
const productSection = document.getElementById("product-section");
let productsArray = [];
fetch("./assets/js/products.json")
.then(res => res.json())
.then(products => {
let productHtml = "";
products.forEach(function(item) {
productsArray.push(item);
//Here I just insert the data to the HTML
});
})
.catch(err => console.log("Error in Fetch: " + err));
console.log(productsArray[0]); //Output: undefined
//The array contains all the items, but I can't access the array items.
Here I try to just assign productsArray with the array from the JSON. But the array is empty outside the fetch. My assumption why this way doesn't work is because I'm just creating a reference to the JSON array inside the fetch, which can't be accessed outside the fetch. Is that correct?
const productSection = document.getElementById("product-section");
let productsArray = [];
fetch("./assets/js/products.json")
.then(res => res.json())
.then(products => {
productsArray = products;
let productHtml = "";
products.forEach(function(item) {
//Here I just insert the data to the HTML
});
})
.catch(err => console.log("Error in Fetch: " + err));
console.log(productsArray); //Output: undefined
//The whole array is empty