We have built a kind of a reusable menu bar which accepts a callback function with a string value of selectedMenuItem. The structure looks similar to the below -
Interface
export default interface MenuItem {
title: string;
id: string;
onClick: (option: string) => void;
}
Initial Value -
[
{
title: "menu1",
id: "MENU_1",
onClick: (option) => {
onMenuClick(option);
}
},
{
title: "menu2",
id: "MENU_2",
onClick: (option) => {
onMenuClick(option);
}
}
]
The onMenuClick will probably have a switch to determine the next flow.
Example -
const onMenuClick = (option) => {
switch (option) {
case TopNavigationMenuItems.Security:
navigate('../security');
break;
case TopNavigationMenuItems.Members:
navigate('../members');
break;
case TopNavigationMenuItems.Budgets:
navigate('../budgets');
break;
case TopNavigationMenuItems.Files:
navigate('../files');
break;
default:
break;
}
};
}
Now, I need to read a value from a state (declared with a useState hook).
The problem is that when the menu button is clicked, it only shows the initial state declared in useState. The new value of the state is not reflected in the callback functions.
I have tried to demonstrate the problem in the codesandbox - https://codesandbox.io/s/winter-glitter-fyk1ud
How can I ensure the callback function always refers to the updated state? Slightly confused here.
If you can recommend better ways of achieving this, that would be extremely helpful too.