Search code examples
reactjsadmin-on-rest

Admin On Rest: Admin component should re-render when a correct login occurs


So I working with users with specific roles and permissions. Two of this roles have is own Dashboard but the rest doesn't. So basically i'm doing something like this on my App.js:

const AdminProps = {
  title: <Header />,
  theme: getMuiTheme(SnapbackTheme),
  locale: 'en',
  restClient,
  authClient: AuthClient,
  loginPage: LoginPage
}

let AppLayout = <Admin {...AdminProps } />

if (userRoleIs(USER_ROLE_1)) {
  AppLayout = (
    <Admin {...AdminProps } dashboard={CustomDashboardForThisRole}>
      <Resource name="resource1" list={resource1List} />
    </Admin>
  )
}

if (userRoleIs(USER_ROLE_2)) {
  AppLayout = (
    <Admin {...AdminProps }>
      <Resource name="resource1" list={resource1List} />
    </Admin>
  )
}

return AppLayout

As you can see, depending of the user that is logged in I can choose which props Admin should have. This is working, kind of, the problem with this is that when you log in with a user and find out which role has I don't have a proper way to update the Admin props and re-render it.

That causes a empty content screen when logging in with users that have custom dashboard until I refresh the page and Admin render correctly with the correct dashboard for the user.

My ugly workaround at the moment: a window.location.reload() when the login was successful but you can see the empty content screen for a second and it looks awful.

My question is: Is there a proper way to re-render the Admin component from the authClient?

Thanks in advance! 👋🏼


Solution

  • The recommended way is to use aor-permissions, which introduces the <WithPermission> and <SwitchPermissions> components. You can use the latter to wrap the parts that need rerendering in your Dashboard:

    import React from 'react';
    import { SwitchPermissions, Permission } from 'aor-permissions';
    import authClient from './authClient';
    
    const Dashboard = () => (
        <SwitchPermissions authClient={authClient}>
            <Permission value={USER_ROLE_1}>
                <CustomDashboardForThisRole />
            </Permission>
        </SwitchPermissions>
    );
    

    Then, import this Dashboard component in your Admin directly.