Hello I am having some trouble with removing items from selectedTags state array onClick. Please see the below react component:
TagPosts.tsx
interface Tag {
id: string;
name: string;
}
const TagPosts: React.FC= () => {
let [tags, setTags] = useState<Tag[]>([]);
let [selectedTags, setSelectedTags] = useState<Tag[]>([]);
// STATE IS BEING UPDATED FINE WITH THE BELOW addToSelected FUNCTION
const addToSelected = (tag: Tag) => {
setSelectedTags([...selectedTags, tag]);
};
// HAVING ISSUE WITH REMOVING ITEMS FROM SELECTED ARRAY. STATE IS NOT BEING UPDATED WITH THE BELOW FUNCTION
const removeFromSelected = (tag: Tag) => {
const index = selectedTags.indexOf(tag);
const newSelectedTags = selectedTags;
newSelectedTags.splice(index, 1);
setSelectedTags(newSelectedTags);
};
const renderTags = tags.map((tag) => {
if (!selectedTags.includes(tag)) {
return (
<StyledTagBox key={tag.id} onClick={() => addToSelected(tag)}>
<Typography variant="displayTags">{tag.name}</Typography>
</StyledTagBox>
);
} else if (selectedTags.includes(tag)) {
return (
<SelectedTagBox key={tag.id} onClick={() => removeFromSelected(tag)}>
<Typography variant="displayTags" color="#fff">
{tag.name}
</Typography>
</SelectedTagBox>
);
}
});
export default TagPosts;
Can anyone spot the bug? The weird thing is that when i console.log the newSelectedTags variable it is showing the desired array but the setSelectedTags function in the line right after is not executing?
Any help would be greatly appreciated. Thanks!
const newSelectedTags = [...selectedTags];