Im still kinda new to Javascript. Right now I'm building a web application where I want to show items from a data.json file and search through those items.
I have a fetchItems()
function where I fetch the data.json. After this I show the items in the index.html
with the initItems()
function.
The problem is that I want those 'items' from the fetch call available in the searchItems()
function too. With these 'items' I plan to filter the items. Unfortunately I'm missing something which is why the console.log
in searchItems.js
gives back undefined
.
I tried different things with async and await but couldn't get that to work either.
index.js
import { fetchItems } from "./src/js/fetchItems";
import { searchItems } from "./src/js/searchItems";
fetchItems();
searchItems();
fetchItems.js
export function fetchItems() {
return fetch("./src/data/data.json")
.then(response => response.json())
.then(items => initItems(items));
}
function initItems(items) {
for (let item of items) {
let appItem = document.createElement("app-item");
let appItems = document.getElementById("app-items");
appItems.appendChild(appItem);
appItem.setAttribute("name", item.name);
appItem.setAttribute("description", item.description);
}
}
searchItems.js
export function searchItems(items) {
console.log(items);
}