enter image description hereI am working on a component AddEmployee which is a form where the detials of the employee can be entered and have two buttons in the form submit (to submit the user data) , reset (to reset the form data). I am using React hook form library. The AddEmployee Component is used both for adding and editing employee detials.

The data is passed from EmployeeList component to AddEmployee component from a prop called userAction for adding i pass a object which has the required property need for the form and form editing employee detials the data i get from react table that i pass to userAction

import { Campaign, Download, Edit } from "@mui/icons-material";
import {
  Box,
  Button,
  IconButton,
  Stack,
  Tooltip,
  Typography,
} from "@mui/material";
import styles from "./EmployeeList.module.css";
import BasicTable from "../../table/BasicTable";
import { useDispatch, useSelector } from "react-redux";
import { useState } from "react";
import AddEmployee from "./AddEmployee";
import Heading from "../../Heading";
import {
  BeachAccess,
  Close,
  CurrencyRupee,
  LocalAtm,
  Lock,
  Person,
  RadioButtonUnchecked,
} from "@mui/icons-material";

function EmployeeList() {
  const employeeList = useSelector((store) => store.employee.employeeList);
  const employee = useSelector((store) => store.employee.employee);
  const [userAction, setUserAction] = useState();
  const [open, setOpen] = useState(false);
  const [showModal, setShowModal] = useState("");

  function handleClickOpen() {
    setUserAction(employee);
    setShowModal("employeeAddEdit");
    setOpen(true);
  }

  function handleEdit(data) {
    setUserAction(data);
    setShowModal("employeeAddEdit");
    setOpen(true);
  }

  const COLUMN = [
    { Header: "S.No", accessor: (_, index) => `${index + 1}` },
    { Header: "User ID", accessor: "code" },
    {
      Header: "Dept",
      accessor: "department",
    },
    { Header: "User", accessor: "userName" },
    { Header: "Name", accessor: "fullName" },
    { Header: "Current Address", accessor: "currentAddress" },
    { Header: "Mobile", accessor: "mobile" },
    { Header: "Salary (Rs.)", accessor: "basicSalary" },
    {
      Header: "Action",
      Cell: ({ row }) => (
        <Stack direction="row">
          <IconButton>
            <BeachAccess className={styles.actionIcons} />
          </IconButton>
          <IconButton onClick={() => handleEdit(row.original)}>
            <Tooltip
              title={<Typography>Edit Profile</Typography>}
              placement="top-start"
              followCursor
            >
              <Edit />
            </Tooltip>
          </IconButton>
          <IconButton>
            <CurrencyRupee className={styles.actionIcons} />
          </IconButton>
          <IconButton>
            <LocalAtm className={styles.actionIcons} />
          </IconButton>
          <IconButton>
            <Tooltip
              title={<Typography>Lock Profile</Typography>}
              placement="top-start"
              followCursor
            >
              <Lock className={styles.actionIcons} />
            </Tooltip>
          </IconButton>
          <IconButton>
            <RadioButtonUnchecked className={styles.actionIcons} />
          </IconButton>
          <IconButton>
            <Download className={styles.actionIcons} />
          </IconButton>
          <IconButton>
            <Tooltip
              title={<Typography>Employee Details</Typography>}
              placement="top-start"
              followCursor
            >
              <Person className={styles.actionIcons} />
            </Tooltip>
          </IconButton>
          <IconButton>
            <Tooltip
              title={<Typography>Remove</Typography>}
              placement="top-start"
              followCursor
            >
              <Close className={styles.actionIcons} />
            </Tooltip>
          </IconButton>
        </Stack>
      ),
    },
  ];

  return (
    <Stack spacing={2}>
      <Heading icon={<Campaign fontSize="large" />} variant="h6">
        All Employee List
      </Heading>
      <Box className={`${styles.flexContainer} ${styles.justifyEnd}`}>
        <Button variant="contained" onClick={handleClickOpen}>
          Add New Employee
        </Button>
        <Button variant="contained">Print</Button>
        <Button variant="contained" startIcon={<Download />}>
          Excel
        </Button>
      </Box>
      {showModal === "employeeAddEdit" && (
        <AddEmployee userAction={userAction} open={open} setOpen={setOpen} />
      )}
      <BasicTable tableColumn={COLUMN} tableData={employeeList} />
    </Stack>
  );
}

export default EmployeeList;

Please help me out for adding the employee the behaviour of the form works fine like when clicked on submit the data is stored in redux and when clicked on reset the form get reset and all the values in textfield are cleared out. But when i edit the form the values that are passed to the component userAction prop all the values are layed out to their repective fields but when clicked on reset the react hook form devtools state is cleared but the form values does not clear out.

import { Box, Button } from "@mui/material";
import styles from "./AddEmployee.module.css";
import Label from "../../Label";

import { useDispatch, useSelector } from "react-redux";

import { Download } from "@mui/icons-material";
import FormModal from "../../FormModal";
import { useForm } from "react-hook-form";
import FormSelect from "../../FormSelect";
import FormTextField from "../../FormTextField";
import { employeeList } from "../../redux/storeslice/employeeSlice";
import { useEffect } from "react";

function AddEmployee({ open, setOpen, userAction }) {
  const employee = useSelector((store) => store.employee.employee);
  const dispatch = useDispatch();
  const form = useForm({
    defaultValues: {
      id: new Date().toISOString(),
      ...userAction,
    },
  });

  const { register, control, handleSubmit, formState, reset } = form;
  const { errors } = formState;

  useEffect(
    function () {
      reset(userAction);
    },
    [reset, userAction]
  );

  function handleClose() {
    setOpen(false);
    reset(employee);
  }

  function onSubmit(data) {
    dispatch(employeeList(data));
    handleClose();
  }

  function handleReset() {
    reset({
      id: new Date().toISOString(),
      ...employee,
    });
  }

  return (
    <FormModal
      open={open}
      setOpen={setOpen}
      handleClose={handleClose}
      control={control}
      submit={handleSubmit(onSubmit)}
      title={"Add Employee"}
      buttonSlot={
        <>
          <Button color="success" variant="contained">
            Print
          </Button>
          <Button color="warning" variant="contained" startIcon={<Download />}>
            Excel
          </Button>
          <Button variant="contained" onClick={handleClose}>
            Hide
          </Button>
        </>
      }
      submitSlot={
        <>
          <Button form="myForm" type="submit" variant="contained">
            Submit
          </Button>
          <Button form="myForm" onClick={handleReset} variant="contained">
            Reset
          </Button>
        </>
      }
    >
      <Box className={styles.container}>
        <Box className={styles.itemContainer}>
          <Label
            htmlFor="department"
            labelName={
              <>
                Department
                <Box component="span" className={styles.important}>
                  *
                </Box>
              </>
            }
          />
          <FormSelect
            id="department"
            control={control}
            values={["Teacher", "House Keeping", "Gate Keeper"]}
            placeholder="Department"
            register={{
              ...register(`department`, {
                required: "*Field cannot be empty",
              }),
            }}
            helperText={errors.department?.message}
            error={errors.department?.message ? true : false}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label
            htmlFor="code"
            labelName={
              <>
                Code
                <Box component="span" className={styles.important}>
                  *
                </Box>
              </>
            }
          />
          <FormTextField
            id="code"
            type="number"
            register={{
              ...register("code", {
                required: "*Field cannot be empty",
                valueAsNumber: true,
              }),
            }}
            disabled={true}
            helperText={errors.code?.message}
            error={errors.code?.message ? true : false}
          />
        </Box>

        <Box className={styles.itemContainer}>
          <Label
            htmlFor="userName"
            labelName={
              <>
                UserName
                <Box component="span" className={styles.important}>
                  *
                </Box>
              </>
            }
          />
          <FormTextField
            id="userName"
            type="text"
            register={{
              ...register("userName", { required: "*Field cannot be empty" }),
            }}
            helperText={errors.userName?.message}
            error={errors.userName?.message ? true : false}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label
            htmlFor="password"
            labelName={
              <>
                Password
                <Box component="span" className={styles.important}>
                  *
                </Box>
              </>
            }
          />
          <FormTextField
            id="password"
            type="password"
            register={{
              ...register("password", { required: "*Field cannot be empty" }),
            }}
            helperText={errors.password?.message}
            error={errors.password?.message ? true : false}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label
            htmlFor="aadharNumber"
            labelName={
              <>
                Aadhar Number
                <Box component="span" className={styles.important}>
                  *
                </Box>
              </>
            }
          />
          <FormTextField
            id="aadharNumber"
            type="number"
            register={{
              ...register("aadharNumber", {
                required: "*Field cannot be empty",
                valueAsNumber: true,
              }),
            }}
            helperText={errors.aadharNumber?.message}
            error={errors.aadharNumber?.message ? true : false}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label
            htmlFor="fullName"
            labelName={
              <>
                Full Name
                <Box component="span" className={styles.important}>
                  *
                </Box>
              </>
            }
          />
          <FormTextField
            id="fullName"
            type="text"
            register={{
              ...register("fullName", {
                required: "*Field cannot be empty",
              }),
            }}
            helperText={errors.fullName?.message}
            error={errors.fullName?.message ? true : false}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label
            htmlFor="fatherName"
            labelName={
              <>
                Father Name
                <Box component="span" className={styles.important}>
                  *
                </Box>
              </>
            }
          />
          <FormTextField
            id="fatherName"
            type="text"
            register={{
              ...register("fatherName", {
                required: "*Field cannot be empty",
              }),
            }}
            helperText={errors.fatherName?.message}
            error={errors.fatherName?.message ? true : false}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label
            htmlFor="subject"
            labelName={
              <>
                Subject
                <Box component="span" className={styles.important}>
                  *
                </Box>
              </>
            }
          />
          <FormTextField
            id="subject"
            type="text"
            register={{
              ...register("subject", {
                required: "*Field cannot be empty",
              }),
            }}
            helperText={errors.subject?.message}
            error={errors.subject?.message ? true : false}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label
            htmlFor="dob"
            labelName={
              <>
                DOB
                <Box component="span" className={styles.important}>
                  *
                </Box>
              </>
            }
          />
          <FormTextField
            id="dob"
            type="date"
            register={{
              ...register("dob", {
                required: "*Field cannot be empty",
                valueAsDate: true,
              }),
            }}
            helperText={errors.dob?.message}
            error={errors.dob?.message ? true : false}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label
            htmlFor="joiningDate"
            labelName={
              <>
                Joining Date
                <Box component="span" className={styles.important}>
                  *
                </Box>
              </>
            }
          />
          <FormTextField
            id="joiningDate"
            type="date"
            register={{
              ...register("joiningDate", {
                required: "*Field cannot be empty",
                valueAsDate: true,
              }),
            }}
            helperText={errors.joiningDate?.message}
            error={errors.joiningDate?.message ? true : false}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label
            htmlFor="education"
            labelName={
              <>
                Education
                <Box component="span" className={styles.important}>
                  *
                </Box>
              </>
            }
          />
          <FormTextField
            id="education"
            type="text"
            register={{
              ...register("education", {
                required: "*Field cannot be empty",
              }),
            }}
            helperText={errors.education?.message}
            error={errors.education?.message ? true : false}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label
            htmlFor="email"
            labelName={
              <>
                Email Address
                <Box component="span" className={styles.important}>
                  *
                </Box>
              </>
            }
          />
          <FormTextField
            id="email"
            type="email"
            register={{
              ...register("email", {
                required: "*Field cannot be empty",
              }),
            }}
            helperText={errors.email?.message}
            error={errors.email?.message ? true : false}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label
            htmlFor="currentAddress"
            labelName={
              <>
                Current Address
                <Box component="span" className={styles.important}>
                  *
                </Box>
              </>
            }
          />
          <FormTextField
            id="currentAddress"
            type="text"
            multiline={true}
            rows={2}
            register={{
              ...register("currentAddress", {
                required: "*Field cannot be empty",
              }),
            }}
            helperText={errors.currentAddress?.message}
            error={errors.currentAddress?.message ? true : false}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label
            htmlFor="permanentAddress"
            labelName={
              <>
                Permanent Address
                <Box component="span" className={styles.important}>
                  *
                </Box>
              </>
            }
          />
          <FormTextField
            id="permanentAddress"
            type="text"
            multiline={true}
            rows={2}
            register={{
              ...register("permanentAddress", {
                required: "*Field cannot be empty",
              }),
            }}
            helperText={errors.permanentAddress?.message}
            error={errors.permanentAddress?.message ? true : false}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label
            htmlFor="mobile"
            labelName={
              <>
                Mobile
                <Box component="span" className={styles.important}>
                  *
                </Box>
              </>
            }
          />
          <FormTextField
            id="mobile"
            type="number"
            register={{
              ...register("mobile", {
                required: "*Field cannot be empty",
                valueAsNumber: true,
              }),
            }}
            helperText={errors.mobile?.message}
            error={errors.mobile?.message ? true : false}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label htmlFor="lastCompany" labelName="Last Company Name" />
          <FormTextField
            id="lastCompany"
            type="text"
            register={{
              ...register("lastCompany"),
            }}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label htmlFor="contact" labelName="Contact" />
          <FormTextField
            id="contact"
            type="number"
            register={{
              ...register("contact", {
                valueAsNumber: true,
              }),
            }}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label htmlFor="emgContact" labelName="Emergency Contact" />
          <FormTextField
            id="emgContact"
            type="number"
            register={{
              ...register("emgContact", {
                valueAsNumber: true,
              }),
            }}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label htmlFor="photo" labelName="Users Photo" />
          <FormTextField
            id="photo"
            type="file"
            register={{
              ...register("photo", {}),
            }}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label htmlFor="basicSalary" labelName="Basic Salary" />
          <FormTextField
            id="basicSalary"
            type="number"
            register={{
              ...register("basicSalary", {
                valueAsNumber: true,
              }),
            }}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label htmlFor="hra" labelName="HRA" />
          <FormTextField
            id="hra"
            type="number"
            register={{
              ...register("hra", {
                valueAsNumber: true,
              }),
            }}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label htmlFor="petrolconv" labelName="Petrol/Conv." />
          <FormTextField
            id="petrolconv"
            type="number"
            register={{
              ...register("petrolconv", {
                valueAsNumber: true,
              }),
            }}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label htmlFor="others" labelName="Others" />
          <FormTextField
            id="others"
            type="number"
            register={{
              ...register("others", {
                valueAsNumber: true,
              }),
            }}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label htmlFor="incentive" labelName="Incentive" />
          <FormTextField
            id="incentive"
            type="number"
            register={{
              ...register("incentive", {
                valueAsNumber: true,
              }),
            }}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label htmlFor="esic" labelName="ESIC No." />
          <FormTextField
            id="esic"
            type="number"
            register={{
              ...register("esic", {
                valueAsNumber: true,
              }),
            }}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label htmlFor="upa" labelName="UPA No." />
          <FormTextField
            id="upa"
            type="number"
            register={{
              ...register("upa", {
                valueAsNumber: true,
              }),
            }}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label htmlFor="grossSalary" labelName="Gross Salary" />
          <FormTextField
            id="grossSalary"
            type="number"
            register={{
              ...register("grossSalary", {
                valueAsNumber: true,
              }),
            }}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label htmlFor="salaryMode" labelName="Salary Mode" />
          <FormSelect
            id="salaryMode"
            placeholder="Salary Mode"
            control={control}
            values={["Cash", "Cheque", "Online"]}
            register={{
              ...register(`salaryMode`),
            }}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label htmlFor="bankName" labelName="Bank Name" />
          <FormTextField
            id="bankName"
            type="text"
            register={{
              ...register("bankName", {}),
            }}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label htmlFor="accNo" labelName="Account No." />
          <FormTextField
            id="accNo"
            type="number"
            register={{
              ...register("accNo", {
                valueAsNumber: true,
              }),
            }}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label htmlFor="remark" labelName="Remarks" />
          <FormTextField
            id="remark"
            type="text"
            register={{
              ...register("remark", {}),
            }}
          />
        </Box>
        <Box className={styles.itemContainer}>
          <Label htmlFor="followRules" labelName="Follow Salary Rules" />

          <FormSelect
            id="salaryRule"
            placeholder="Salary Rule"
            control={control}
            values={["Yes", "No"]}
            register={{
              ...register(`salaryRule`),
            }}
          />
        </Box>
      </Box>
    </FormModal>
  );
}

export default AddEmployee;

0

There are 0 best solutions below