Using Fetch to Load Local JSON

Hey all,

Just a bit of a random question regarding best practices. I am finishing making a website and and using a local JSON file to store data I need in one of the pages.

I have decided to keep the data in a separate JSON as it has the potential to become pretty big and I want to account for the future so it isn’t an issue for me or the next person who develops the project.

In order to do so I have used a simple fetch query to get the data:

                fetch('./assets/json/spices.json')
                .then(res => res.json())
                .then(data => {
                  console.log(data)
                })
                .catch(err => console.error(err));

However, I am aware that I can also export the data as a module by saving it as a .js filetype and using the ES6 export/import as follows:

                let spices =  await import('./assets/json/spices.js')
                .then(res => res.json())
                .then(data => {
                  console.log(data)
                })
                .catch(err => console.error(err));

To me it seems that both approaches achieve the same results (asynchronously get the data) however, the ES6 import/export module method, to me, seems to use more code.

Which would be considered to be best practice? Or is there another method which I have missed?

Is it actually important that it is loaded dynamically, or is it effectively a configuration file of data? Because you can just do:

import spices from "./assets/spices.js";

// Then use the data in the `spices` object here

The difference in the amount of code is almost nonexistent as well. Just importing JS is probably simpler and lets you put comments and things in the JS, but it relies on the dynamic import statement being available in the user’s browser, whereas fetch is better supported.

Also, you’re mixing async/await and promise syntax: not a biggie, but it’s a bit easier if you pick one or the other.

1 Like

Thank for replying Dan! It isn’t really important for it to be dynamically loaded at all, I just instantly thought of fetch to be the ideal solution. I realise that simply using the import/export as a module is probably the best bet.

I was originally having trouble when I tried implementing your method then realised I needed to add the type="module" to my script when calling it in the head.

I never actually realised that I was doing that until you have just mentioned it! Duly noted!

Thank you again.

1 Like