skip to Main Content

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;

enter image description here

i tried this

3

Answers


  1. Try

    users.forEach((user) => { total += user.salary; });

    instead of

    setUsers.forEach((users) => { total += users.salary; });

    setUser is the function which modifies the users state. You want to loop the users, not the function.

    Login or Signup to reply.
  2. In your case you should use for each on the users state not on the setUsers setter.

    useState hook return an Array which has two items, the variable which hold the state and a function to update that state value.

    function Calculation()
    {
        let sum = 0;
    
        users.forEach((user) => {
            sum+= user.salary;
        });
    
        setTot(sum)
    
        return sum;
    }
    

    Also you should have not defined total as that will be obtain after calling the Calculation function. Or you can call setTot to update the totol state once

    Another point you could use Array.prototype.reduce function instead of map funciton. That will be like this

    function calculation()
    {
        let sum = users.reduce((accumulator, current) => {
            accumulator = accumulator + current.salary;
            return accumulator;
        }, 0);
        setTot(sum);
        return sum;
    }
    
    Login or Signup to reply.
  3. You have to use setTot to set total state and reduce function for total count instead forEach

    function Calculation()
    {
      setUsers([...users,{ name, salary}]);
       
      const total = users.reduce((total,user)=>{
        total += Number(user.salary)
        return total
      }),0);
      setTot(total); // you want this
    }
    

    Use defaultValue prop instead value

     <input type="text" defaultValue={total} class="form-control" placeholder="Enter Total" 
        onChange={(event) =>
            {
              setTot(event.target.value);      
            }}
    />
    

    Use key prop so react must understand which one to update

     {users.map((row,index) => (
                <tr key={index}>
                  <td>{row.name}</td>
                  <td>{row.salary}</td>
                </tr>
      ))}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search