Skip to content

form.reset #41

Open
Open
@usmankhanXislabs

Description

@usmankhanXislabs

I am working on a React-based customer form component where a user can create or edit customer details, including assigning customer groups using a MultiSelect component. The data for customerGroupList is fetched from an API, and the selected groups are dynamically mapped to the form.

The issue is that when editing a customer, the selectedGroups array is sometimes empty, even though the customerForEdit.customerGroup contains valid data. This results in the form not pre-filling the MultiSelect with the correct options.

'use client';
import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { useSelector, useDispatch } from 'react-redux';
import * as customersActions from '../../app/redux/cutomers/cutomersActions';
import { useCustomerGroupList } from '@/config/customerGroupsSearchHook';
import { MultiSelect } from '../multi-select';

export const CustomerForm: React.FC = () => {
const dispatch = useDispatch();
const { customerGroupList } = useCustomerGroupList();
const [selectedCustomerGroups, setSelectedCustomerGroups] = useState<string[]>([]);

const form = useForm({
defaultValues: {
_id: '',
name: '',
email: '',
address: '',
mobile: '',
zip: '',
businessName: '',
customerGroup: [],
},
});

const {
customers: { customerForEdit },
}: any = useSelector((state: RootState) => ({
customers: state.customers,
}));

useEffect(() => {
if (customerForEdit && customerForEdit?._id) {
const selectedGroups = customerGroupList.filter((group) =>
customerForEdit.customerGroup.includes(group.value)
);

  const updatedData = {
    _id: customerForEdit._id,
    name: customerForEdit.name,
    address: customerForEdit.address,
    businessName: customerForEdit.businessName,
    zip: customerForEdit.zip,
    mobile: customerForEdit.mobile,
    email: customerForEdit.email,
    customerGroup: selectedGroups.map((item) => item.value),
  };

  form.reset(updatedData);
  setSelectedCustomerGroups(updatedData.customerGroup);
} else {
  form.reset({
    _id: '',
    name: '',
    email: '',
    address: '',
    mobile: '',
    zip: '',
    businessName: '',
    customerGroup: [],
  });
}

}, [customerForEdit, customerGroupList]);

const onSubmit = async (data) => {
const updatedData = {
...data,
customerGroup: selectedCustomerGroups,
};
console.log('Form submitted:', updatedData);
};

return (


{/* Other fields */}

Submit

);
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions