Home > Software engineering >  How to reload the JSON data on every onclick event in javascript?
How to reload the JSON data on every onclick event in javascript?

Time:10-23

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.

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?

CodePudding user response:

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
});
  • Related