SO as the title states im running into an issue with my react code that whenever i try and remove an item from the array it clears the state entirely (back to [])
My current code looks like this:
import { useState } from "react";
// Berries Container
export function Berries({
filterOptions,
selectedBerries,
setSelectedBerries,
}) {
// set our active berry, this is just for css styling to allow the berry to be toggled on or off
const [activeBerry, setActiveBerry] = useState(false);
let berries = [];
const deleteItem = (name) => {
setSelectedBerries((selectedBerries) =>
selectedBerries.filter((item) => item.name === name)
);
};
function handleActiveBerry(e) {
// toggles the berry on or off
setActiveBerry((activeBerry) => !activeBerry);
if (!activeBerry) {
setSelectedBerries([...selectedBerries, e]);
}
if (activeBerry) {
deleteItem(filterOptions.name);
}
}
return (
<div className="filter-berries-item">
<ul className={!activeBerry ? "berries" : "berries-activated"}>
<img
value={filterOptions.name}
onClick={() => handleActiveBerry(filterOptions.name)}
src={filterOptions.image}
width={20}
height={20}
/>
</ul>
</div>
);
}
The filter options is an object that is passed in and right now im trying to get the name property to append to the list when the item is clicked (toggled to true) and removed when it's clicked again (toggled to false)
So far I have tried a few options, including using the deleteItem function created above. This was suggested in another, yet similar question and did not work.
Edit1: I have also tried selectedBerries.filter((item) => item.name === name))
and it just does not remove an entry at all
Edit 2:
The filterOptions is pretty much an object structured like so
export const testFilter = {
berries: [
{
id: 1,
name: "belue",
get image() {
return belue;
},
},
}
And passed down through props. I then get the name and add it as the arg for handle active berry and delete item
Found the answer to my question. Needed to use a change of syntax and args on the callback function.
Originally I tried to do it like this filtering the berries by selections and wrong syntax with no return. But after trying to convert it to a set and realizing I need to correct my syntax..
const deleteItem = (name) => {
setSelectedBerries((selectedBerries) =>
selectedBerries.filter((item) => item.name === name)
);
};
I changed it from that to this:
const deleteBerries = (berryName) => {
setSelectedBerries((selectedBerries) =>
selectedBerries.filter((selectedName) => {
return selectedName !== berryName;
})
);
};