Basically I have an array called "Heroes" and through buttons I'm trying to add or delete certain items from that array to another one called "favorites". When adding a hero to favorites, the message "item added to favorites!" appears, but the part in which I display my favorites in the document appears to show a blank space instead of the hero's name like I want to. Also, the part of showing "item already added" or "favorites list full" doesn't work. Also, when trying to add more than a hero to favorites, it doesn't allow me to. I don't know what I'm doing wrong. The "clear favorites" button works just fine, and the "remove favorite" appears to do so as well.
´´´
const [favorites, setFavorites] = useState([]);
const [message, setMessage] = useState("");
const addToFavorites = (id) => {
if (favorites.includes((heroin) => heroin.id === id)){
setMessage("hero already in favorites!")
} if (favorites.length = 6) {
setMessage("favorites list full!")
}
const newFavorites = favorites.concat(heroin => heroin.id === id)
setFavorites(newFavorites)
setMessage("item added to favorites!")
}
const deleteFavorite = (id) => {
const newFavorites = favorites.filter((heroin) => heroin.id !== id)
setFavorites(newFavorites);
setMessage("");
}
{heroes.map((heroin)=>{
const {id, props} = heroin;
return <div key={id}><h1>{props}</h1></div>;
})
<button onClick={clearFavorites}>Clear favorites</button>
<button value={id} onClick={()=>addToFavorites(id)}>
Add to favorites</button>
<button value={id} onClick={()=> deleteFavorite(id)}>remove favorite</button>
<h4>{message}</h4>
{favorites.map((favorite)=>{
const {name} = favorite;
return (
<div>
<h1>{name}</h1>
</div>
)
})}
´´´
You are calling array functions that don't take callbacks.
Array.prorotype.includes takes a value, not a predicate function. Since the favorites array doesn't have an exact strictly equal version of the (heroin) => heroin.id === id) function, false is returned because no element can match.Array.prototype.concat will add whatever the value is that is passed to to a new copy of the array and return the array.favorites.length = 6 is attempting to assign a value to the length property.Code:
const addToFavorites = (id) => {
if (favorites.includes((heroin) => heroin.id === id)) { // Always false!
setMessage("hero already in favorites!");
}
if (favorites.length = 6) {
setMessage("favorites list full!");
}
const newFavorites = favorites.concat(heroin => heroin.id === id); // only adds function instead of hero object
setFavorites(newFavorites);
setMessage("item added to favorites!");
}
Array.prototype.find to search the array for a specific value using a predicate function.Code:
const addToFavorites = (id) => {
const hero = favorites.find((heroin) => heroin.id === id);
if (hero) {
setMessage("hero already in favorites!");
} else {
if (favorites.length === 6) {
setMessage("favorites list full!");
} else {
setFavorites(favorites => favorites.concat(hero));
setMessage("item added to favorites!");
}
}
}