Ethan M
Ethan M

Reputation: 39

UseState how to set an Array back to empty?

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

Answers (3)

Farhad Rad
Farhad Rad

Reputation: 577

There are two issues with the code

  1. filter function seems to be invalid it should be replaced with
clickFavIconArray.filter(item => id != item)
  1. You are adding id again to the array with this
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

Cobra_8
Cobra_8

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

Audwin Oyong
Audwin Oyong

Reputation: 2531

Simply pass the new value of empty array to setClickFavIconArray():

setClickFavIconArray([])

Upvotes: 1

Related Questions