Best way to have a default dynamic value derived from other atom [Recoil]

Viewed 47

I am developing an app, which has sidebar menu. I have an atom, which saves the state of the /menu and an atom which saves the last selected menu key (as this key is used for other selectors too) -> for getting specific info for the current selected key.

export const menuItems = atom({
  key: "menuItems",
  default: ({ get }) => get(baseApi)("/menu"),
}); -> Returns Menu Items

And then I have an atom, which saves the selected menu item key:

export const selectedMenuKey = atom<string>({
  key: "selectedMenuKey",
});

I cannot prefix the initial selected menu key as I don't know it in advance. I want the behavior to be following:

If the key is not set (when the app initially runs) set the selectedMenuKey value to be the first item of the menuItems atom value, otherwise be whatever is set last.

What would you say is the best way to achieve this?

0 Answers
Related