12

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

3
  • @Pranshu Saxena show your Input component code. Commented Mar 31, 2020 at 11:21
  • @VahidAkhtar He is using Ant Design. Commented Mar 31, 2020 at 11:23
  • did you log response.data.name inside then? Commented Mar 31, 2020 at 11:24

1 Answer 1

31

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.