Reputation: 5088
Hello I would like to use Antd with ReactJS to create a Json with nested objects without having to parse the form into a interface or some other structure.
I am super new to react and antd and I thought this syntax would work, but it does not.
<Form.Item name={['supplier', 'phone']} label="Telefone" >
<Input />
</Form.Item>
<Form.Item name={['supplier.address', 'adress1']} label="Endereço">
<Input />
</Form.Item>
<Form.Item name={['supplier.address', 'adress2']} label="Complemento">
<Input />
</Form.Item>
into this
"phone": 1231231,
"address": [
{
"adress1": "string",
"adress2": "string"
}]
}
My sender
javascript const onFinish = async (values: Store) => {
console.log(values);
let response = await axios.post(
'http://0.0.0.0:8080/suppliers',
values.supplier ,
{ headers: { 'Content-Type': 'application/json' } }
)
console.log(response.data)
};
But that does not send any of the address part of it, what is the best way to do this?
Thanks
Upvotes: 1
Views: 3546
Reputation: 11156
Ciao, here working example.
Basically, on onFinish
function, I get values
object and create the object that you want like this:
const onFinish = values => {
let result = {};
result.address = [];
result.phone = values.phone;
let addresses = {};
addresses.address1 = values.address1;
addresses.address2 = values.address2;
result.address.push(addresses);
console.log("Success:", result);
};
Upvotes: 1
Reputation: 61
You need to use Form.List to put values into array. Look at the example: https://ant.design/components/form/#Form.List
That's how I would do it:
<Form initialValues={{phone: '', address: [ 'val1', 'val2' ]}}>
<Form.Item name={'phone'} label="Telefone" >
<Input />
</Form.Item>
<Form.List>
{fields => (
<Form.Item name={[ fields.name, 'address' + fields.name]} label="Endereço">
<Input />
</Form.Item>
)}
</Form.List>
</Form>
Upvotes: 2