I have this imaginary case where I have a function that has a form, which I can update my data. It is a real estate agency and wants to have option to update its properties when the sellers makes some changes. Note that data might not make much sense irl but it is just for learning purpose.
A property object looks like this:
{
owner: "John doe",
other: {
rooms: 3,
windows: 6
}
address: {
street: "jane doe",
houseNr: 24
}
}
And my component:
import React, { useState } from 'react'
import { connect } from 'react-redux'
import { getProperty } from '../../actions'
const Property = ({ getProperty, property }) => {
const [propertyObj, setPropertyObj] = useState(property);
const { propertyId, owner, address, other } = propertyObj
const propertyAddress = `${address.street}, ${address.houseNr}` // jane doe, 24
const { rooms } = other;
const handleSubmit = (event) => {
event.preventDefault()
// todo: submit the updated property
}
return (
<div className='row align-items-start'>
<div className='col col-md-6'>
<p>Id: {propertyId}</p>
<form>
<div className='row'>
<label className='mt-3'>Owner</label><input className='ml-3' type='text' name='owner' onChange={e => setPropertyObj({ owner: e.target.value })} defaultValue={owner} />
</div>
<div className='row'>
<label className='mt-3 mx-3'>Rooms</label><input className='ml-3' type='text' name='rooms' onChange={e => setPropertyObj({ rooms: e.target.value })} defaultValue={rooms} />
<div className='row'>
<label className='mt-3 mx-3'>Property Address</label><input className='ml-3' type='text' name='propertyAddress' onChange={e => setPropertyObj({ propertyAddress: e.target.value })} defaultValue={propertyAddress} />
</div>
</form>
</div>
<button onClick={(e) => handleSubmit(e)} className='btn btn-success'>Update Property</button>
</div>
)
}
const mapStateToProps = reduxStoreState => {
return {
property: reduxStoreState.property,
}
}
export default connect(mapStateToProps, { getProperty })(Property)
When attempting to update rooms property, I get:
TypeError: other is undefined
But I beliver I would get a similar error when I would try to update the property address.
I know that for property address, I have to split into street and house number to update each separately. The question is how can I update the state variable property so that I can submit that to my function updatePropertyById(id, updatedProperty), I have seen ways to do in cases when it is a class object, but I want to use the new features of react.
How can I update the rooms for instance, without needing to also type the windows, I think the spread operator would be helpful but I just don't know how.