'entered value only shows in console reactjs
I'm making an expense handler app using reactjs in a practical course. Now, I'm supposed to make a new row with the data I'm passing through form. But it only shows up in console. The code is as such:
App.js
Now in Expense form, I have a submit handler and some states:
const ExpenseForm = (props) => {
const [enteredTitle, setEnteredTitle] = useState('');
const [enteredAmount, setEnteredAmount] = useState('');
const [enteredDate, setEnteredDate] = useState('');
const titleChangeHandler = (event) => {
setEnteredTitle(event.target.value);
};
const amountChangeHandler = (event) => {
setEnteredAmount(event.target.value);
};
const dateChangeHandler = (event) => {
setEnteredDate(event.target.value);
};
const submitHandler = (event) => {
event.preventDefault();
const expenseData = {
title: enteredTitle,
amount: enteredAmount,
date: new Date(enteredDate),
};
props.onSaveExpenseData(expenseData);
setEnteredTitle('');
setEnteredAmount('');
setEnteredDate('');
};
return (
<form onSubmit={submitHandler}>
<div className='new-expense__controls'>
<div className='new-expense__control'>
<label>Title</label>
<input
type='text'
value={enteredTitle}
onChange={titleChangeHandler}
/>
</div>
<div className='new-expense__control'>
<label>Amount</label>
<input
type='number'
min='0.01'
step='0.01'
value={enteredAmount}
onChange={amountChangeHandler}
/>
</div>
<div className='new-expense__control'>
<label>Date</label>
<input
type='date'
min='2019-01-01'
max='2022-12-31'
value={enteredDate}
onChange={dateChangeHandler}
/>
</div>
</div>
<div className='new-expense__actions'>
<button type='submit'>Add Expense</button>
</div>
</form>
);
};
The last part is for newExpense:
Can anyone tell why I can't make a new row with the data I'm passing through the form?
Solution 1:[1]
But it only shows up in console.
As far as the code is concerned, you are only getting the new row in console because you are printing the object in the console in line number 30.
I understand from your question that you need to display the data you entered in the form when you click on submit. For this to happen, you have to make the following adjustments in your code:
- put the array of expenses in a state, this will re-render the component whenever you add a new data.
- after line number 30, in your
addExpenseHandler
, add the new object to the expenses state.
something like this:
const [expenses, setExpenses] = useState([<your-initial-data>]);
...
...
...
const addExpenseHandler = expense => {
console.log(expense);
setExpenses(prevArray => prevArray.push(expense));
}
...
...
...
Hopefully this solves your questions.
Cheers!
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 | abhishekti7 |