'When I try to push an element to a array but it takes only one rest of the elements are got removed automatically. It happen when use useState hook
const [filter, setFilter] = useState([]);
let brandList = [];
const handleCheckBox = (e) => {
const { value, checked } = e.target;
if (checked) {
brandList.push(value);
} else {
let ind = brandList.indexOf(value);
brandList.splice(ind, 1);
}
console.log(brandList);
setFilter([...brandList]);
};
When I try to push an element to an array but it takes only one rest of the elements are got removed automatically. It happens when I using the useState hook.
Please checkout the image below:

Solution 1:[1]
brandList is redeclared an empty array each render cycle. This is why you only ever see that last filter item value added.
Use the filter state directly.
Example:
const [filter, setFilter] = useState([]);
const handleCheckBox = (e) => {
const { value, checked } = e.target;
if (checked) {
setFilter(filter => [...filter, value]);
} else {
setFilter(filter => filter.filter(el => el !== value));
}
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Drew Reese |
