I am creating a weather dashboard and am trying to save the city name to local storage. I already have the logic written to have the city post in the history section I just can’t get the data to stay there after I reload the page. I have checked and it is saving to local storage but just not retrieving it. Here is the fetch call and the code underneath where I am trying to save the localStorage:
fetch( 'https://api.openweathermap.org/data/2.5/weather?q=' + searchCity + '&units=imperial&appid=64a50easdasdda68eb7a2b92c0bc02b65b123123121234593' ) .then(function (response) { return response.json(); }) .then(function (data) { // localStorage.setItem(data.name, JSON.stringify(data)); getCity(data); getTemp(data); getWS(data); getHumid(data) getForecast(data) getCityLast(data) }) } function getCityLast(data) { var saveCity = data.name var saveCityDiv = document.createElement('button') saveCityDiv.classList.add('list-item') var saveCityText = document.createTextNode(saveCity) saveCityDiv.appendChild(saveCityText) getLastCity.appendChild(saveCityDiv) localStorage.setItem(data.name, JSON.stringify(data)); console.log(localStorage.key(data)) for (let i = 0; i < localStorage.length; i++) { var key = localStorage.key(i) getLastCity.saveCityDiv += `${key}` } }
Advertisement
Answer
To retrieve your persisted stringified JSON data, you want to do this:
for (let i = 0; i < localStorage.length; i++) { const key = localStorage.key(i) const data = localStorage.getItem(key) console.log(`${key} - ${data}`) }