I'm building a React 16.13.0 application. In my form, I want to submit data (an address) as part of an array, so I set up my state like so ...
constructor(props) {
super(props);
this.state = {
countries: [],
provinces: [],
errors: [],
newCoop: {
name: '',
types: [],
addresses: [{
formatted: '',
locality: {
name: '',
postal_code: '',
state: ''
},
country: FormContainer.DEFAULT_COUNTRY,
}],
enabled: true,
email: '',
phone: '',
web_site: ''
},
I then created these functions for managing changes to the input fields ...
handleInput(e) {
let self=this
let value = e.target.value;
let name = e.target.name;
this.setValue(self.state.newCoop,name,value)
}
setValue = (obj,is, value) => {
if (typeof is == 'string')
return this.setValue(obj,is.split('.'), value);
else if (is.length === 1 && value!==undefined) {
return this.setState({obj: obj[is[0]] = value});
} else if (is.length === 0)
return obj;
else
return this.setValue(obj[is[0]],is.slice(1), value);
}
...
<Input inputType={'text'}
title= {'Street'}
name= {'addresses[0].formatted'}
value={this.state.newCoop.addresses[0].formatted}
placeholder = {'Enter address street'}
handleChange = {this.handleInput}
errors = {this.state.errors}
/> {/* Address street of the cooperative */}
The Input.jsx file looks like the below ...
const Input = (props) => {
return (
<div className="form-group">
<FormLabel>{props.title}</FormLabel>
<FormControl
isInvalid={props.errors && Boolean(props.errors[props.name])}
type={props.type}
id={props.name}
name={props.name}
value={props.value}
placeholder={props.placeholder}
onChange={props.handleChange}
/>
{props.errors && props.errors[props.name] && (
<FormControl.Feedback type="invalid">
{props.errors[props.name].map((error, index) => (
<div key={`field-error-${props.name}-${index}`} className="fieldError">{error}</div>
))}
</FormControl.Feedback>
)}
</div>
)
}
export default Input;
However, when I attempt to change the value, I get the below error. I'm not sure what else I need to be doing to name my component such that I can successfully change it's value. I would prefer not to change the data structure in my constructor, but I'm willing to if that's what it takes.
TypeError: Cannot set property 'formatted' of undefined
FormContainer.setValue
src/containers/FormContainer.jsx:127
124 | if (typeof is == 'string')
125 | return this.setValue(obj,is.split('.'), value);
126 | else if (is.length === 1 && value!==undefined) {
> 127 | return this.setState({obj: obj[is[0]] = value});
| ^
128 | } else if (is.length === 0)
129 | return obj;
130 | else