Reputation: 39
I'm trying set clickFavIconArray
back to an empty array with the hook.
Basically, the setClickFavIconArray
has a list of IDs the showFavIcon()
checks that ID and if it contains the same ID I want to remove it from the array and update the setClickFavIconArray
to the new Array.
However, it just seems to be adding on to the original clickFavIconArray
no matter what. Is there a way to clear the clickFavIconArray
state back to an []
empty array?
Some help here would be awesome.
const [clickFavIconArray, setClickFavIconArray] = useState([]);
function showFavIcon(id){
if (clickFavIconArray.includes(id)) {
const newArray = clickFavIconArray.filter(item => !id.includes(item))
setClickFavIconArray(newArray)
}
setClickFavIconArray([...clickFavIconArray, id])
}
Upvotes: 2
Views: 1093
Reputation: 577
There are two issues with the code
clickFavIconArray.filter(item => id != item)
setClickFavIconArray([...clickFavIconArray, id])
If you want to remove id, there is no need for this line in your code.
However you can always set clickFavIconArray
to an empty array state using this code:
setClickFavIconArray([])
Upvotes: 1
Reputation: 199
To make sure that the id is not immediately added to the array again, add a return statement inside the if-statement.
const [clickFavIconArray, setClickFavIconArray] = useState([]);
function showFavIcon(id){
if (clickFavIconArray.includes(id)) {
const newArray = clickFavIconArray.filter(item => !id.includes(item));
setClickFavIconArray(newArray);
return; // make sure that the next line is not executed
}
setClickFavIconArray([...clickFavIconArray, id])
}
Upvotes: 1
Reputation: 2531
Simply pass the new value of empty array to setClickFavIconArray()
:
setClickFavIconArray([])
Upvotes: 1