function App() {
// const item = 'mango';
const itemList = [];
const [item, updateItm] = useState();
// listening to onChange of input.
const listenInput = function (e) {
// insert item to list
updateItm(e.target.value);
}
const addItem = function() {
let pv = item;
itemList.push(pv);
console.log(itemList);
}
return (
<>
<div className='main-div'>
<div className='center-div'>
<h1>To Do</h1>
<input
onChange={listenInput}
type='text'
name='item'
placeholder='Add item'
/>
<button onClick={addItem}>+</button>
<ol>
<li>{item}</li>
</ol>
</div>
</div>
</>
);
}
i need it to append the itemList with value of pv.
but every time i enter new value in input it replaces the older value.
What i get
let say pv = 'mango'. then itemList = ['mango'] again when i set pv = 'apple' thn itemList = ['apple']
What i want
let say pv = 'mango'. then itemList = ['mango'] again when i set pv = 'apple' thn itemList = ['mango','apple']
2
Answers
i got it. For every updation by useState it re-render the App() function thus re innitializing the itemList so every time i update item my App() reload and set itemList to null.
You should append the value to the
itemList
array in theaddItem
function when the user clicks the button.