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:
JavaScript
x
41
41
1
fetch(
2
'https://api.openweathermap.org/data/2.5/weather?q=' + searchCity + '&units=imperial&appid=64a50easdasdda68eb7a2b92c0bc02b65b123123121234593'
3
)
4
5
.then(function (response) {
6
7
return response.json();
8
})
9
10
.then(function (data) {
11
// localStorage.setItem(data.name, JSON.stringify(data));
12
getCity(data);
13
getTemp(data);
14
getWS(data);
15
getHumid(data)
16
getForecast(data)
17
getCityLast(data)
18
})
19
20
}
21
22
function getCityLast(data) {
23
var saveCity = data.name
24
var saveCityDiv = document.createElement('button')
25
26
saveCityDiv.classList.add('list-item')
27
var saveCityText = document.createTextNode(saveCity)
28
saveCityDiv.appendChild(saveCityText)
29
getLastCity.appendChild(saveCityDiv)
30
31
localStorage.setItem(data.name, JSON.stringify(data));
32
33
console.log(localStorage.key(data))
34
35
for (let i = 0; i < localStorage.length; i++) {
36
var key = localStorage.key(i)
37
38
getLastCity.saveCityDiv += `${key}`
39
}
40
}
41
Advertisement
Answer
To retrieve your persisted stringified JSON data, you want to do this:
JavaScript
1
6
1
for (let i = 0; i < localStorage.length; i++) {
2
const key = localStorage.key(i)
3
const data = localStorage.getItem(key)
4
console.log(`${key} - ${data}`)
5
}
6