Sushilzzz
Sushilzzz

Reputation: 577

In react hooks form, how to you copy data from one property to other of state?

This is register form, I want to send the value orgTypes>name to orgType of data of same object using onChange of select.

https://codesandbox.io/s/react-typescript-zm1ov?fontsize=14&fbclid=IwAR06ZifrKrDT_JFb0A-d_iu5YaSyuQ9qvLRgqS20JgAcSwLtAyaOFOoj5IQ

When I use onChange of Select, it erases all other data of the inputs.

import React from "react";
import { Select } from "antd";
const { Option } = Select;

const RegisterFinal = () => {
  const data = {
    orgName: "",
    orgRegNo: "",
    orgType: "",

    orgTypes: [
      { id: "1", name: "Vendor" },
      { id: "2", name: "Supplier" },
      { id: "3", name: "Vendor and Supplier" }
    ],

    errors: {}
  };

  const [values, setValues] = React.useState(data);

  const handleChange = (e: any) => {
    e.persist();
    setValues((values: any) => ({
      ...values,
      [e.target.name]: e.target.value
    }));
  };
  const handleSubmit = () => {
    console.log(values);
  };

  return (
    <React.Fragment>
      <input
        name="orgName"
        onChange={handleChange}
        placeholder="Organization Name"
        value={values.orgName}
      />
      <input
        name="orgRegNo"
        onChange={handleChange}
        placeholder="Registration Number"
        value={values.orgRegNo}
      />

      <Select //imported from antd
        id="select"
        defaultValue="Choose"
        onChange={(select: any) => {
          setValues(select);
          console.log(select); //shows Vender/Supplier, I want this value to be sent to orgType above
        }}
      >
        {data.orgTypes.map((option: any) => (
          <Option key={option.id} value={option.name}>
            {option.name}
          </Option>
        ))}
      </Select>
    </React.Fragment>
  );
};

When I use onChange of Select, it erases all other data of the inputs.

Thank you for your help

Upvotes: 1

Views: 595

Answers (1)

3b3ziz
3b3ziz

Reputation: 911

setValues function expects to take the values object as an argument. Instead you are passing the select value to it.

Instead, you can do it like this:

const handleSelectChange = (selectValue: any) => {
    setValues((values: any) => ({
      ...values,
      orgType: selectValue
    }));
}

and use handleSelectChange in the onChange of your select.

Check the solution here: https://codesandbox.io/s/react-typescript-p9bjz

Upvotes: 1

Related Questions