Issue
When i clicking "add to favorites" button, I want to store its data as a localStorage value only once.
If it exists in localStorage, a second click must have no effect (just an alert).
How to do that in angular ionic ?
heres my working application and sample code
https://weather4133.netlify.app/
https://github.com/Novian227/WeatherAppIonic
save() {
let data = [];
let w = JSON.parse(localStorage.getItem('fav'));
if (w != null) {
for (let i=0; i<w.length; i++) {
data.push(w[i]);
}
}
data.push(this.weather);
localStorage.setItem('fav', JSON.stringify(data));
}
Solution
EDIT : So this.weather is object instead of string.
Using indexOf would have been feasible had your array only contained primitive types such as numbers, strings etc. but as your array contains objects, it needs a different approach.
So you need to use findIndex to check existence of object on array.
save() {
let data = JSON.parse(localStorage.getItem('fav')) || [],
isExist = data.findIndex((obj) => {
// Compare all keys here to validate "uniqueness"
// You can add many keys as you like
return obj.date == this.weather.date && obj.temp == this.weather.temp;
}) != -1;
if (isExist) {
// show alert here
} else {
data.push(this.weather);
localStorage.setItem('fav', JSON.stringify(data));
}
}
Answered By - byakugie
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.