0

I want to create a mobx store that is only loaded by admin users. It will only be injected into anything along the /admin route. I've looked into the use of Nested Providers but without much luck.

Ideally I'd like it to be linked to the route, so if a user goes to domain.com/admin then it is loaded.

I could write botchy code that simply checks if the user is admin, but I'm hoping theres a more elegant pattern I could follow.

EDIT

heres my temporary solution, let me know if theres a better way

AdminRoutes

export const AdminRoutes = () => {
    
    const adminStores = createAdminStores()
    return (
        <Switch>
            <Provider {...adminStores}>
                <AuthedRoute path="/admin" exact component={Admin} />
            </Provider>
        </Switch>
    )
};

App.ts

export const App = hot(({ history }: any) => (
<Provider {...rootStores}/>
  <Router history={history}>

    <Switch>

      <UnauthedRoute path="/login" exact component={Login}></UnauthedRoute>

      <Route path="/admin" exact component={AdminRoutes} />

      <Route path="/error" component={ErrorComponent} />
      <Route path="/abc" component={Test} />

      <Route path="/:path" component={Issue} />
      <Route path="/" component={Home} />

    </Switch>
  </Router>
</Provider>
));

I create the admin stores only when the user runs the AdminRoutes route. The only issue with this is that the store reloads when the user changes the URL however that happens with all my other stores.

Marc Frame
  • 923
  • 1
  • 13
  • 26

1 Answers1

1

One thing you could improve is to use React.lazy with your whole Admin component.

// import it like that
const AdminRoutes = React.lazy(() => import('./path-to-admin-routes'))
...
// and use like that
<Route
  path="/admin"
  render={() => (
    <Suspense fallback={'Loading'}>
      <AdminRoutes />
    </Suspense>
  )}
/>

That way regular non-admin users won't even load admin stuff and your final bundle will be smaller.

More info: https://reactjs.org/docs/code-splitting.html#reactlazy

Or you could also inject your AdminStore inside RootStore dynamically. I made example for it, hope it makes sense https://codesandbox.io/s/httpsstackoverflowcomquestions62759240-ew8hf?file=/src/AdminComponent.js Basically you create your AdminStore first time admin component is loaded and then use newly created instance by saving it inside RootStore

Danila
  • 15,606
  • 2
  • 35
  • 67