defaultValue or value not working on FormItem ANTD
The docs states that:
You cannot set value of form control via value defaultValue prop, and you should set default value with initialValue in getFieldDecorator instead.
You shouldn't call setState manually, please use this.props.form.setFieldsValue to change value programmatically.
So you just need to call setFieldsValue
when the data is loaded from the backend:
fetch('http://localhost:5728/Fields/get/' + this.state.Data.Id)
.then(results=>{
return results.json()
})
.then(data=>{
this.props.form.setFieldsValue({
Id: data.field.Id,
Name: data.field.Name,
Description: data.field.Description,
Value: data.field.Value
})
})
Or shorter, if data.field
from backend totally matches the field names:
this.props.form.setFieldsValue(data.field)
you can use hook, too
import { Form } from "antd"
const [form] = Form.useForm();
fetch('api')
.then(results=>{
return results.json()
})
.then(data=>{
form.setFieldsValue({
sample: data.dataYouWant
});
<Form form = {form}>
<Form.Item name = "sample">
<Input />
</Form.Item>
</Form>
For Class component V4:
class Demo extends React.Component {
formRef = React.createRef();
componentDidMount() {
this.formRef.current.setFieldsValue({
username: 'Bamboo',
});
}
render() {
return (
<Form ref={this.formRef}>
<Form.Item name="username" rules={[{ required: true }]}>
<Input />
</Form.Item>
</Form>
);
}
}