i have an array of json object which contains title and array of subtitles and i have a select option where am storing the title lists and i made a loop on the subtitles array so i can add inputs depending on the subtitles length the problem is that when i select first item it works fine but when i select the second item from the dropdown list it doesn't see the new update of the array so it shows me an error of undefined because the state didn't update correctly i didn't know how to solve it
here is my array :
constructor(props) {
super(props);
this.state = {
Modules_SubModules_Array: [{
"Module": "",
"SubModules": []
}],
};
}
and then there is the function that i execute when i select item from dropdown list :
Affect_Module_Submodule = (currentModuleTitle, index) => {
if (
this.state.Modules_SubModules_Array.findIndex(
item => item.Module == currentModuleTitle
) < 0
) {
this.state.Modules_SubModules_Array.splice(index, 1, {
Module: currentModuleTitle,
SubModules: []
});
this.setState({
Modules_SubModules_Array: this.state.Modules_SubModules_Array
});
}
};
and there is the loop that i use :
values.Modules_SubModules_Array[this.state.selectedIndex].SubModules.map(
(subModule, index2) => {
return (
<div key={index2}>
<TextFields
style={{ marginLeft: "15%" }}
defaultValue={subModule}
hintText="SubModule Title"
floatingLabelText="SubModule Title"
onChange={e =>
this.props.handleSubModuleChange(
e,
index2,
this.state.selectedIndex,
this.state.result,
values.subModuleTitle
)
}
/>
<input
type="button"
value="remove"
onClick={() =>
this.props.removeSubModule(index2, this.state.result)
}
/>
<br />
<br />
</div>
);
}
);
the selectIndex is the index of the json object which contains the title that i selected from the dropdown list
so when i select a first item from the select the loop works and when i try to change to a second item from the select it won't work it tells me cannot read SubModules of undefined because in my console it prints undefined then it prints the new state so of course it won't work because he sees undefined at first didn't know how to solve it