im sorry everyone to bug you..im new with reactjs and i really dont know why everytime i click "X" button in my functional component adding new empty line inside my map() my expectation is when i click "X" button its only log me something in my console. is anyone here can help explain what is happening and how to solve this? below here i post my code. please advise, thank you so much.
import './App.css';
import React, { useEffect, useState } from 'react';
import uniqid from 'uniqid';
function App() {
const [heldItems, setHeldItems] = useState({
salesno: '',
plu: '',
price: 0,
dateandtime: '',
});
const [salesItemsTemp, setSalesItemsTemp] = useState([]);
const handlerOnChange = (e) => {
let heldItemsTemp = { ...heldItems };
heldItemsTemp.salesno = uniqid();
heldItemsTemp[e.target.name] = e.target.value;
heldItemsTemp.dateandtime = new Date().toLocaleString();
console.log(heldItemsTemp);
setHeldItems(heldItemsTemp);
};
const handlerOnSubmit = (e) => {
e.preventDefault();
setSalesItemsTemp([...salesItemsTemp, { heldItems }]);
setHeldItems({
salesno: '',
plu: '',
price: 0,
dateandtime: '',
});
};
const handlerRemove = () => {
console.log('its from handlerRemove !');
};
useEffect(
() => console.log('helditems', heldItems),
[heldItems],
);
return (
<>
<form onSubmit={handlerOnSubmit} autoComplete="off">
<h1>POS</h1>
<input
type="text"
placeholder="Input item name"
name="plu"
onChange={handlerOnChange}
value={heldItems.plu}
/>
PLU
<input
type="number"
placeholder="Input item price"
name="price"
onChange={handlerOnChange}
value={heldItems.price}
/>
Price
<button type="submit">add item</button>
<div>
<ul>
{salesItemsTemp.map((sales) => {
console.log('mapping sales', sales);
const { salesno, plu, price, dateandtime } =
sales.heldItems;
return (
<li key={salesno}>
<p>salesno : {salesno}</p>
<p>plu : {plu}</p>
<p>price : {price}</p>
<p>dateandtime : {dateandtime}</p>
<button onClick={handlerRemove}>X</button>
</li>
);
})}
</ul>
</div>
</form>
</>
);
}
export default App;
CodePudding user response:
You're submitting your form when you're pressing the X button here:
<form onSubmit={handlerOnSubmit} autoComplete="off">
which is running the following line in your handlerOnSubmit
function, adding an empty entry to your items.
setSalesItemsTemp([...salesItemsTemp, { heldItems }]);
Use type="button"
on your X button to prevent the form submitting. Alternatively, move the submit handler to an onClick event on the submit button, rather than on the form.