0

I have following code,

import create from "zustand";
import { useAuth } from "react-oidc-context";
import UserService from "../../services/authentication/userService";

type UserStore = {
    role: string,
    setRole: () => void
}

const auth = useAuth();

const useUserStore = create<UserStore>((set, get) => ({
    role: getRole, //how to return getRole value?
    setRole: () => {
        UserService.getUserRole(auth.user.access_token).then((res) =>
            set((state) => ({
                ...state,
                role: res
            }))
        )
    },
    getRole: () => {
        const role = get().role;
        if (!role) {
            get().setRole();
        }

        return role;
    }
}));

export default useUserStore

I want role value to come from getRole function, how do I do that?

tickwave
  • 3,335
  • 6
  • 41
  • 82
  • Are you talking about the type definition or actual logic? – Akash Sep 26 '21 at 11:49
  • if you want `role` to be the result of calling getRole, simply call the `getRole()` function. It will now be like this `role: getRole(),` – Akash Sep 26 '21 at 11:49
  • @Akash: Doing `role: getRole()` resulted with an error message `Cannot find name 'getRole'` – tickwave Sep 26 '21 at 11:50
  • it's because the `getRole()` function is defined after the `role` field – Akash Sep 26 '21 at 11:51
  • I understood your problem, let me post an answer – Akash Sep 26 '21 at 11:52
  • What should the getRole here return? The line `role: getRole` should have default value. So something like `role: null` – martin.malek Sep 26 '21 at 12:08
  • so, the idea is that in my component I would simply do `const user = useUserStore()`, then I would simply do `user.role` to check the `role` of the user. Is that possible? – tickwave Sep 26 '21 at 12:10
  • So the component that use this `userStore` will not call `getRole` or `setRole` at all, it will simply call `user.role`. Then the `role` will call `getRole` method, `getRole` will check whether `role` has value, if not, then it will call `setRole`. – tickwave Sep 26 '21 at 12:11
  • I understand that my current code will probably not work due to `getRole` will call itself over and over, I came from C# and usually we use private variable and then do the setter getter, is that possible in typescript? – tickwave Sep 26 '21 at 12:17
  • You could try `get role() { return this.getRole() }` – Alex Chashin Sep 26 '21 at 16:36

0 Answers0