i want to calculate the final total of the salary.when i add enter the data on the form data should append on the form and values are calculating and display the final total on the total textbox. when i enter the data and click submit button i got the error was
setUsers.forEach is not a function
TypeError: setUsers.forEach is not a function
what i tried so far i attached below.please rectify the eror
import { useState } from "react";
function Test() {
const [name, setName] = useState();
const [salary, setSalary] = useState();
const [users, setUsers] = useState([]);
var [total, setTot] = useState();
function Calculation()
{
setUsers([...users,{ name, salary}]);
users.forEach((user) => {
newTotal += Number(user.salary);
});
setTot(newTotal);
}
return (
<div class="container">
<h3>Employee Salary Calculation</h3>
<div class="form-group">
<label>Employee Name</label>
<input type="text" class="form-control" placeholder="Employee Name"
onChange={(event) =>
{
setName(event.target.value);
}}
/>
</div>
<div class="form-group">
<label>Salary</label>
<input type="text" class="form-control" placeholder="Enter Salary"
onChange={(event) =>
{
setSalary(event.target.value);
}}
/>
</div>
<div class="form-group">
<label>Total</label>
<input type="text" class="form-control" placeholder="Enter Total"
onChange={(event) =>
{
setTot(event.target.value);
}}
/>
</div>
<button type="submit" onClick={Calculation} class="btn btn-primary mt-4">Submit</button>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{users.map((row ) => (
<tr>
<td>{row .name}</td>
<td>{row .salary}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
export default Test;
i tried this
3
Answers
Try
users.forEach((user) => { total += user.salary; });
instead of
setUsers.forEach((users) => { total += users.salary; });
setUser
is the function which modifies theusers
state. You want to loop the users, not the function.In your case you should use for each on the
users
state not on thesetUsers
setter.useState
hook return an Array which has two items, the variable which hold the state and a function to update that state value.Also you should have not defined
total
as that will be obtain after calling theCalculation
function. Or you can callsetTot
to update thetotol
state onceAnother point you could use
Array.prototype.reduce
function instead ofmap
funciton. That will be like thisYou have to use
setTot
to set total state andreduce
function for total count insteadforEach
Use
defaultValue
prop insteadvalue
Use
key
prop so react must understand which one to update