Background:
I am using antd select component in my form for tagging. This form is used to update the backend on changes on an entity. Hence on first load, I would like to update the select component to show the existing tags. To do so, I used the form.setFieldsValue
method to update the form. (there are some other fields as well)
Problem
When using setFieldsValue
, I inserted a LabelObject
with the tags label and value. If I do not update the tags field, the form value seems to stay as the object rather than the value and will submit the form with the tags field as objects.
How do i get the tags field to update with the initial value while allowing my tags to display correctly?
Code snippets
const UpdateForm = ({ initialValues }) => {
useEffect(() => {
if (initialValues) {
let formDisplayValue = { ...initialValues }
form.setFieldsValue({
...formDisplayValue,
country: formDisplayValue.country.code,
tags: formDisplayValue.tags?.map((val) => {
return { value: val.id, label: val.name, name: val.name }
})
});
}
}, [form, initialValues]);
return (
<Form
form={form}
name="basic"
autoComplete="off"
>
...
<TagSelectComponent />
</Form>
)
}
const TagSelectComponent = () => {
const [searchData, setSearchData] = useState([]);
const [value, setValue] = useState();
const handleSearch = async (newValue) => {
const { data } = await searchTags(newValue);
setSearchData((data?.tags || []).map((val) => { return { value: val.id, label: val.name } }))
};
const handleChange = (newValue) => {
setValue(newValue);
};
return <Form.Item label="Tags" name="tags">
<Select
mode="multiple"
showSearch
value={value}
placeholder={"tags"}
defaultActiveFirstOption={false}
suffixIcon={null}
filterOption={false}
onSearch={handleSearch}
onChange={handleChange}
notFoundContent={null}
options={(searchData || []).map((d) => ({
value: d.value,
label: d.label,
}))}
labelRender={(val) => {
return val.label
}}
/>
</Form.Item>
}
I kind of understand that setting the fields value using setFieldsValue
is causing the form value to be set as the object passed in. but i do not know how i am able to get the tags to still display correctly (with the labels) if i just set the correct value.
Note: I do not want to add another API call just to get the tag info for update as i feel is quite wasteful.