'Correct way to push an item to array in javascript
I am pushing a new item to the array. when a function call."
const tagItem=[];
function handleSelectOption(title, item) {
setCompareTagTitle(title);
tagItem.push(item);
console.log(tagItem)
if (title !== compareTagTitle) {
setCounter(++counter);
} else if (title === compareTagTitle) {
setCounter(counter);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
when the function call at first time it pushes an item in the array, but when the function calls the second time it looks like it overwrites the item and pushes the new item correctly after that.
This is the photo:
The expected result is:
['c++','php', 'java', 'JavaScript']
But it gives me:
['php', 'java', 'JavaScript']
Solution 1:[1]
Try adding a local state to your component.
const [tagItem, setTagItem] = useState([]);
function handleSelectOption(title, item) {
setCompareTagTitle(title);
setTagItem([...tagItem, item]);
console.log(tagItem)
if (title !== compareTagTitle) {
setCounter(++counter);
} else if (title === compareTagTitle) {
setCounter(counter);
}
}
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 | Kim Skovhus Andersen |

