Access JSON data from content representation in Javascript

Hi everyone,

after creating a contntent representation (like decribed in the cookbook) i now need to access the JSON data im my JS file (preferably as a const). The following code doesn’t work so far:

fetch('/home.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(articles) {
    const data = (JSON.stringify(articles));
  });
  
const items = document.querySelectorAll(".item");

items.forEach((item, index) => {
  item.addEventListener("click", () => {
updateOverlay(data[index]);
  });
});

function updateOverlay(dataItem) {
    const itemCopy = document.querySelector("#item-copy");
  itemCopy.innerHTML = dataItem.itemCopy;
}

the json file looks fine and is loaded properly but the console throws the error: data is not defined

The problem is scope, your data constant is only known inside that callback function (or whatever that is called in JS), not outside.

Ah, right. Solved it:

fetch ('/home.json')
.then (function (response) {
return response.json();
}).then (function (data) {
appendData (data);
});
function appendData (data) {...}