Reputation: 23
I have a React state object called formData with user checkout shipping data and inside formData there is another object called billingAdress which contains user billing data.
state = {
user: null,
formData: {
name: null,
company: null,
adressOne: null,
adressTwo: null,
town: null,
postcode: null,
country: null,
phone: null,
isBillingAdress: false,
billingAdress: {
name: null,
company: null,
adressOne: null,
adressTwo: null,
town: null,
postcode: null,
country: null,
phone: null,
}}
There is onChange function on input
<label>Full Name:</label>
<input
name="name"
onChange={this.handleBillingChange}
value={this.state.formData.billingAdress.name}
/>
Function looks like this
handleBillingChange = event => {
const formData = { ...this.state.formData, billingAdress: {[event.target.name]: event.target.value }}
const errors = { ...this.state.errors, [event.target.name]: '' }
this.setState({ formData, errors})
}
Im trying to store whole billingAdress object inside of formData object, when I start typing in the first billing adress input, it works well, but when i start typing in a second input, first input disappear from a state.
Upvotes: 0
Views: 431
Reputation: 2565
The problem lies in your handleBillingChange
function.
Try this in order to keep the current state of formData.billingAdress
when changing one property.
const handleBillingChange = event => {
const formData = {
...this.state.formData,
billingAdress: {
...this.state.formData.billingAdress,
[event.target.name]: event.target.value
}
}
const errors = { ...this.state.errors, [event.target.name]: '' }
this.setState({ formData, errors})
}
Upvotes: 0