Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to reload the JSON data on every onclick event in javascript?

I have this code where I import the JSON data into a variable, and then i modify that data:

import jsondata1 from '../project.json' assert {type: 'json'};
var jsondata1s = JSON.stringify(jsondata1)
document.getElementById("project-btn").onclick ...

The JSON data gets changed on other processes, so everytime that I click on the button I want to re-import the JSON data updated, something that would look like this:

document.getElementById("project-btn").onclick onclick = () => {
    //import jsondata1 from '../project.json' assert {type: 'json'};
    var jsondata1s = JSON.stringify(jsondata1)
}

So everytime i click on the button the JSON data gets updated, but this JSON line cannot be at a function.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I achieve this?

Is there any other way maybe that I can import the JSON data in a line without needing to be at the beginning?

>Solution :

You can not use the import declaration like that. One solution is to fetch() the json file when wanted (make a request). Like this:

fetch(".../project.json")
.then(response => response.json())
.then(json => {
    console.log(json):
    //Do something with json variable
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading