Issue
I have data coming back from the db like so:
[{"id":"a7e45e4c-4af1-477e-9642-759fff49d44e","name":"Gallons","unitSize":[50,5,25]},
{"id":"5c607a2c-9388-4c09-a0dc-c6cd1d35a9c9","name":"lbs","unitSize":[30,90,60]}],
"errors":null}]
I have two dropdowns, one maps the Units of Measure (name) and its working great, I now want to create a new list for the second dropdown, which returns only the Unit Sizes (unitSize) for the selected Units Of Measure. The problem I am having is that react wont let me map through my list. Here is what it says:
UPDATE In my code, within the renderUnitSize function, my uosArr which is holding the specific data i want is working correctly, this is where I am now trying to set the data into uosList. Howeve I console.log it after I setState and my uoslist is empty. It is an array, however I am assuming this error is coming because its not holding any data?
public state = {
uosList: [],
};
public returnUnitSizes = () => {
const product = this.state.product;
const uom = product.unit;
const uosArr = this.state.unitOfMeasures.find(um => um.name === uom);
this.setState({
uosList: uosArr
});
console.log();
}
public handleUOMChange(event: any) {
const product = this.state.product;
product.unit = event.target.value;
this.setState({
product
}, () => this.returnUnitSizes());
console.log(product);
}
<FormGroup className="required">
<Label>Unit of Measure</Label>
<EInput
type="select"
name="unitOfMeasure"
id="unitOfMeasure"
value={this.state.product.unit}
onChange={this.handleUOMChange}
required={true}
>
<option />
{this.state.unitOfMeasures.map((UOM: IUnitOfMeasure,
index: number) =>
<option key={UOM.id} value={UOM.name}>{UOM.name}
</option>
)}
</EInput>
</FormGroup>
<FormGroup className="required">
<Label>Unit Size</Label>
<EInput
type="select"
name="unitOfMeasure"
value={this.state.product.size}
onChange={this.handleUnitSizeChange}
disabled={this.state.unitOfMeasure.id !== ''}
required={true}
>
<option />
{this.state.uosList && this.state.uosList.map((uosList: any, index: number) =>
<option key={index} value={uosList[index]}>{uosList}</option>
)
}
</EInput>
</FormGroup>
Solution
Your mistakes lies in this function:
public returnUnitSizes = () => {
const product = this.state.product;
const uom = product.unit;
const uosArr = this.state.unitOfMeasures.find(um => um.name === uom);
this.setState({
uosList: uosArr
});
console.log();
}
You are setting uosList to uosArr. But uosArr refers to an element of the array this.state.unitOfMeasures. As you wrote, this is an object with the shape:
{
id: string,
name: string,
unitSize: Array,
}
In reality you want to set uosList to uosArr.unitSize.
Answered By - MarcRo


0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.