简体   繁体   中英

Best practice for updating dynamic api values in html tags

I am fetching api information every minute updating a dashboard.

An example of the payload is

      "dew_point": "46.6", 
      "humidity": "44.0", 
      "is_cloudy": "Cloudy", 
      "is_raining": "No", 
      "is_wet": "No", 
      "temperature": "69.4", 
      "timestamp": "2020-08-28 22:53:44", 
      "wind_speed": "2.2"

I have a div full of p's that populate with that data and the API payload is saved in a variable called data.

Currently, I am updating this data by doing

// Api data saved in data
var data = response;
var temperatureText = document.getElementById("temperatureText");
temperatureText.textContent = data.temperature;

However, in my application, the api is returning about 50 data entries. I feel like I am hardcoding this update process, and using some formatting on tag id's and the api names could make this easier in some loop.

What is the correct process on updating this data? Should I change the ids of my text paragraphs to match the API payload and loop through? Should I build the div with the API response on the first loading of the page, call each paragraph the name of the API data then loop through updating in future api calls?

I want to make this as modular as possible.

Two possible approaches here:

1- Keep an array of the property names within the data you want displayed and do as you suggested, make ID's in elements have formats that are consistent with payload properties.

Then loop over the array of properties you want displayed and insert in DOM

Simple example:

 const data={dew_point:"46.6",humidity:"44.0",is_cloudy:"Cloudy",is_raining:"No",is_wet:"No",temperature:"69.4",timestamp:"2020-08-28 22:53:44",wind_speed:"2.2"}; const wanted_keys = ["dew_point", "temperature"]; wanted_keys.forEach(k => document.getElementById('w-' + k).textContent = data[k])
 Dew: <span id="w-dew_point"></span>, Temp:<span id="w-temperature"></span>

OR

2- Do the reverse and store the associated property names in data- attributes on the elements that all have common class and loop over the collection inserting text found by the properrty in the data attribute

 const data={dew_point:"46.6",humidity:"44.0",is_cloudy:"Cloudy",is_raining:"No",is_wet:"No",temperature:"69.4",timestamp:"2020-08-28 22:53:44",wind_speed:"2.2"}; document.querySelectorAll('.w-data').forEach(el=> el.textContent = data[el.dataset.key])
 Dew: <span class="w-data" data-key="dew_point"></span>, Temp:<span class="w-data" data-key="temperature"></span>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM