0

I've the items.js file that add the items in the page, the navigation.js that detect the click on the items and the main.js that load both files.

The problem is that since the items are loaded dynamic, the navigation.js must be loaded after the items.js.

I've solved this by adding a setTimeout to the navigation.js import.

My doubt is: there's a better way to do that without the setTimeout?

main.js

import items from './_items.js';
import navigation from './_navigation.js';

items();

setTimeout(() => {
    navigation();
}, 1000);

items.js

export default function () {
    fetch('files/items.json').then(function(response) {
        return response.json();
    }).then(function(data) {
        let body = '';
    
        data.map(function(item) {
            body += `<a href="#" class="link">${item.name}</a>`;
        });

        let div = document.getElementById('items');
        div.innerHTML = body;
    });
}

navigation.js

export default function () {
    const links = document.querySelectorAll('.link');

    links.forEach(el => el.addEventListener('click', event => {
        event.preventDefault();

        console.log('Click!');
    }));
}
Diego Vieira
  • 189
  • 1
  • 5
  • 15
  • 1
    It does not matter which order the functions are _loaded_ or _imported_ in. You need to `await` the `fetch` call. Since `items` doesn’t return anything, the `Promise` returned by `fetch` is unreachable. Just return `fetch`, then do `await items(); navigation();`. – Sebastian Simon Dec 03 '22 at 15:11
  • It worked! Thanks @SebastianSimon. I had tried to use await but I forgot to return the fetch. – Diego Vieira Dec 03 '22 at 15:14

0 Answers0