Reputation: 79
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: [],
Upvotes: 2
Views: 70
Reputation: 202741
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;
})
...
}
state
looks to be an array of [<city>, <country>]
pairs while favorites is an array of these pairs, i.e. [[<city>, <country>]]
.
Use array destructuring assignment to get city
and country
from the favorites
array to compare agains state
's city
and country
.
const addFavoriteCity = (state) => {
const included = favorites.some(([city, country]) => {
const [stateCity, stateCountry] = state;
return (
city.toLowerCase() === stateCity.toLowerCase() &&
country.toLowerCase() === stateCountry.toLowerCase()
);
});
if (!included) {
setFavorites((favorites) => [...favorites, state]);
}
};
Upvotes: 1