This is my first time using React hooks and I have stumbled across a problem I can't solve. I am using the formAmount hook to get the input value of store it in state.amount. When that happens the amount is supposed to reduce totaling to a number whenever a user puts it in. The problem is that I can't make a new array in the onChange event because it catalogs every stroke of the key and it doesn't give me the complete number and I can't set it directly on the state.amount. How can I get that amount and store in an array?
Here is my code:
const Transactions = () => {
const [state, setState] = useState([
{
expense: [],
amount: [],
id: ''
}
])
const [formExpense, setFormExpense] = useState('')
const [formAmount, setFormAmount] = useState([])
const handleSubmit = (e) => {
e.preventDefault();
addExpense()
e.target.reset()
}
// add total of array of amount
let sum = formAmount.reduce((accumulator, currentValue) => {
{ return accumulator += currentValue }
}, 0)
// push value of input to array
const addExpense = (e) => {
setState([...state, { expense: formExpense, amount: [...formAmount], id: Math.random() * 100 }])
}
return (
<div className="transactions">
<div className="expenses">
<form onSubmit={handleSubmit}>
<input
type="text"
id="expense"
className="formfield"
name="expense"
placeholder="Expense..."
onChange={(e) => setFormExpense(e.target.value)}
/>
<input
type="text"
id="amount"
className="formfield"
name="amount"
placeholder="Amount..."
onChange={(e) => setFormAmount([Number(e.target.value)])}
/>
<button type="submit">Submit</button>
</form>
</div>
<div className="finalbalance ">
<div className="finalexpense final">
Total Expense
{'$' + sum.toLocaleString()}
{
state.map(stat => {
return (
<div key={stat.id}>
<h3 className="outputexpense output">{stat.expense + stat.amount}</h3>
</div>
)
})
}
</div>
</div>
</div>
)
}