I am struggling with handling a list with useState in React. I have to add an item to the list twice in a row, and only the second item is added. The code:
App.js
import React, { useState } from "react";
import ItemForm from "./itemForm";
function App() {
const [itemList, setItemList] = useState([]);
function addItem(item) {
setItemList([...itemList, item]);
}
return (
<div>
<ItemForm onAddItem={ addItem } />
{ itemList &&
itemList.map((item, i) => <ul key={ i + itemList } >{ item }</ul>) }
</div>
);
}
export default App;
ItemForm.js
import React, { useState } from 'react';
function ItemForm({ onAddItem }) {
const [inputValue, setInputValue] = useState('');
function handleSubmit(e) {
e.preventDefault();
var item = e.target.item.value;
// Here, I have to call onAddItem twice.
onAddItem(item);
onAddItem(item + " second time");
}
return (
<div>
<form onSubmit={ handleSubmit } >
<input value={ inputValue }
onChange={(e) => setInputValue(e.target.value) } name="item"></input>
<button type="submit">Add</button>
</form>
</div>
)
}
export default ItemForm;
This is the actual behavior of the app:
And this is the expected behavior:
why this happens and how can I fix it?

