i want to display the list of item data in a select menu for the selected items.
i have two select menus. in the first select menu i display types as options which can be type1 or type2. now once user selects the option type1, in the second select menu i will list the items for type1. if user selects the option type2 in the second select menu i will list the items for type2.
have two array of objects namely type1 and type2 like below
const type1 = [
{
id: '1',
name: 'one',
description: 'jj',
type: 'type1',
},
{
id: '2',
name: 'two',
description: 'kk',
type: 'type1',
}
];
const type2 = [
{
id: '3',
name: 'three',
description: 'll',
type: 'type2',
},
{
id: '4',
name: 'four',
description: 'mm',
type: 'type2',
}
];
i will combine those two array of objects combined to one array (alltypes). i will display the alltypes as options in first select menu.
once user selects the type i should set the options for second select menu to type1Data if type1 is selected in first select menu.
type2Data if type2 is selected in second select menu.
below is the code.
const App = () => {
const alltypesData = [
...type1,
...type2,
];
const firstSelectMenuOptions= alldata.map((data: any) => {
return {
label: data.name,
value: data.typename,
};
});
const type1Data = fetchDataforType1;
const type2Data = fetchDataforType2;
let secondMenu = [];
const handleFirstSelectMenuOnchange = (value) => {
if (value === 'type1'){
secondMenu = get(type1Data, 'types.data');
console.log('secondMenu inside', secondMenu); //prints array
} else if (value === 'type2'){
secondMenu = get(type2Data, 'types.data');
} else {
secondMenu = [];
}
);
console.log('secondmenu outside', secondMenu); //prints empty array
const secondMenuOptions = secondMenu.map((data) => {
return {
label: data.name,
value: data.id,
}
});
return (
<Select
options={allData}
value={somevalue}
onChange={(option) => handleFirstSelectMenuOnchange(option.value)}
/>
<Select
options={secondMenuOptions}
/>
);
}
the problem with above code is that the secondMenu value is empty array. so no options are listed in second select menu.
when i log the value of secondMenu inside handleFirstSelectMenuOnchange method is not empty array.
but logging secondMenu value outside the handleFirstSelectMenuOnchange method is empty array.
not sure what is wrong. could someone help me fix this. thanks.
question from:
https://stackoverflow.com/questions/65893690/why-doesnt-the-variable-secondmenu-update-on-choosing-an-option-from-select-menu