Reputation: 25
i'm tring to make a form for a simple application that should update some data to a backend.
Into the form i have multiple inputs, right now i'm handling all the inputs with one onChange handler, as soon as i added a datepicker i'm not able to access his value or update the state with the date picked.
the error i get is : 'Uncaught TypeError: Cannot read properties of undefined (reading 'value')'
I know that antd datepicker need an handler that did not receive an event but a moment object and a strign ( according to antd documentation here)
The big question now is, how can i update the state with that date?
best option would be using one single handler, but the most important thing is to update the state.
here my code:
const Nuovo = ( )=> {
const [lavorazione, setLavorazione] = useState({
numero : 0,
date:'',
nome :'',
cognome : '',
nomeAzienda: '',
modello :'',
targa : '',
telefono : '',
mail : '',
quantità: 0 ,
misura : '',
marca : '',
cerchi :'' ,
})
const [success, setSuccess]= useState(false)
const dateFormat = 'DD/MM/YYYY'
// updating db
const addLavorazione = (lavorazione)=>{
const db = getDatabase();
set(ref(db,'lavorazione/'+ lavorazione.numero),lavorazione)
setSuccess(true);
clear()
console.log('[LAVORAZIONE]',lavorazione)
console.log('[PRE-TIMEOUT',success)
setTimeout(()=>{
setSuccess(false)
console.log('[TIMEOUT]',success)
},5000)
}
//2WAY BINDING FORM
function onChange (e){
const value = e.target.value;
setLavorazione({
...lavorazione,
[e.target.name]:value
});
console.log('[CHANGE-VALUE]', value)
}
const [form] = Form.useForm();
const clear =()=>{
form.resetFields()
}
return(
<Form
form={form}
layout='vertical'
onFinish={addLavorazione}
autoComplete="off">
<Row >
<Col lg={12} xs={24} sm={24} className='form-container'>
<h2>CODICE LAVORAZIONE</h2>
<Form.Item
name="numero"
label="Numero"
rules={[{ required: true }, ]}
>
<Input placeholder='Numero'
value={lavorazione.numero}
name='numero'
onChange={onChange} />
</Form.Item>
<Space direction="vertical">
<DatePicker onChange={onChange} format ={dateFormat} placeholder='Scegli la Data' name='date' value={lavorazione.date} />
</Space>
<h2>ANAGRAFICA CLIENTE</h2>
<Form.Item
name="nome"
label="Nome"
rules={[{ required: true }, { type: 'string', min: 3 }]}
>
<Input placeholder='Nome'
value={lavorazione.nome}
name='nome'
onChange={onChange} />
</Form.Item>
<Form.Item
name="cognome"
label="Cognome"
rules={[{ required: true }, { type: 'string', min: 3 }]}
>
<Input placeholder='Cognome'
value={lavorazione.cognome }
name='cognome'
onChange={onChange} />
</Form.Item>
//... many other inputs down here
</Col>
</Row>
</Form>
)
}
export default Nuovo
thank you in advance to everyone for your time!!!!
Upvotes: 0
Views: 2512
Reputation: 1066
You can pass custom object to onChange
function
<DatePicker
onChange={(value) =>
onChange({ target: { value, name: "date" } })
}
format={dateFormat}
placeholder="Scegli la Data"
name="date"
value={lavorazione.date}
/>
Upvotes: 1