How to make a condition that would check for the presence of elements in the array. I would like the function to add to favorites once
const addFavoriteCity = (state) => {
const newFavotiteList = [...favorites, state];
setFavorites(newFavotiteList);
saveToLocalStorage(newFavotiteList);
}
The favorites array looks like ["London", "GB"], the firts element is the city, the second is the country.
State:
city: undefined,
country: undefined,
lat: undefined,
lon: undefined,
img: undefined,
temp: undefined,
feel: undefined,
descr: undefined,
humidity: undefined,
pressure: undefined,
visibility: undefined,
dt: undefined,
hourlyForecast: [],
dailyForecast: [],
CodePudding user response:
You can do it this way :
const addFavoriteCity = (state) => {
if (favorites.some((f) => f.city === state.city && f.country === state.country)) {
return;
}
const newFavotiteList = [...favorites, state];
setFavorites(newFavotiteList);
saveToLocalStorage(newFavotiteList);
};
CodePudding user response:
You can use Array.prototype.includes in the case that favorites stores primitives or you are able to use strict object equality (typically not the case in React) or you can use Array.prototype.some with a predicate function.
.includes
const addFavoriteCity = (state) => {
const included = favorites.includes(state);
if (included) {
// logic if value in the array
} else {
// logic if not in the array
}
...
}
.some
const addFavoriteCity = (state) => {
const included = favorites.some(el => {
// return some el property equals some state property, etc...
});
if (included) {
// logic if value in the array
} else {
// logic if not in the array
}
...
}
I suggest applying the condition in a functional state update so you are also correctly referencing the previous state object instead of the one closed over in callback scope.
Example:
const addFavoriteCity = (state) => {
setFavorites(list => {
if (!list.some(el => el.city === state.city && el.county === state.county)) {
// not included, add to state
return [...list, state];
}
// included, just return current state
return list;
})
...
}
Update
The
favoritesarray looks like["London", "GB"], the first element is thecity, the second is thecountry.
and
state
city: undefined, country: undefined, ... dailyForecast: [],
Use array destructuring assignment to get city and country from the favorites array to compare agains state.city and state.country.
const addFavoriteCity = (state) => {
const [city, country] = favorites;
const included = state.city === city && state.country === country;
if (included) {
// logic if value included
} else {
// logic if not included
}
...
}
