Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ant Design Input Component not updating value

Tags:

reactjs

antd

I try to get value from backend and append the result to the input field value, but it will not be updated.

Currently I use Ant Design Forms and if input field is moved out of Form it works.

import { version, Input, Form } from "antd";

function View() {
      const [LegalName, setLegalName] = useState("");

    useEffect(() => {
        axios
          .get("/afterlogin/OrgFullPictureGet/3", config)
          .then(response => {
            setLegalName(response.data.name);

          })
          .catch(error => {
            // console.log(error.response.data.errors);
          });
      }, []);

      const onFinish = values => {
        //onFinish logic here
        console.log(values);
      };
      return (
        <div className="App">
          <Form name="nest-messages" onFinish={onFinish}>
            <Form.Item
              name={["user", "LegalName"]}
              label={<span>Legal Name</span>}

            >
              <Input
                placeholder={"Your business legal name"}
                value={LegalName}
                onChange={e => setLegalName(e.target.value)}
              />
            </Form.Item>
          </Form>


        </div>
      );
    }

the value does not get appended on the input field

like image 972
Pranshu Saxena Avatar asked Mar 31 '20 11:03

Pranshu Saxena


1 Answers

When using name field on the Form.Item, it means that the Form component will handle the value and handleChange on the field from then on. You do not need need to add them. So if you need to add value and handleChange, remove name prop from Form.Item as you see here

But using in most cases, you would want to use them. In that case the alternative is to use the form.setFieldValues to set the required values:

const [form] = Form.useForm();
const [legalName, setLegalName] = useState("");

useEffect(() => {
  axios
    .get("/afterlogin/OrgFullPictureGet/3", config)
    .then(response => {
      form.setFieldsValue({
        legalName: response.data.name
      });
    })
    .catch(error => {
      // console.log(error.response.data.errors);
    });
}, []);

return (
  <Form name="nest-messages" form={form} onFinish={onFinish}>
    <Form.Item name="legalName" label={<span>Legal Name</span>}>
      <Input placeholder={"Your business legal name"} />
    </Form.Item>
  </Form>
);

useForm & setFieldValue Demo docs

Stackblitz Demo

like image 161
Agney Avatar answered Oct 27 '22 03:10

Agney