Skip to content

Instantly share code, notes, and snippets.

@brunokiafuka
Last active November 29, 2021 18:34
Show Gist options
  • Save brunokiafuka/f832df8e6c07f1f2e6407a563ea1eb95 to your computer and use it in GitHub Desktop.
Save brunokiafuka/f832df8e6c07f1f2e6407a563ea1eb95 to your computer and use it in GitHub Desktop.
Mobx+React-router navigation
import { createBrowserHistory } from "history";
import { injectable } from "inversify";
import { makeAutoObservable } from "mobx";
import { useClassStore } from "../util/useClassStore";
import container from "./ioc";
@injectable()
class NavigationStore {
history = createBrowserHistory();
constructor() {
makeAutoObservable(this);
}
push = (path: string, state?: any) => {
this.history.push(path, state);
};
replace = (path: string, state?: any) => {
this.history.replace(path, state);
};
go = (n: number) => {
this.history.go(n);
};
goBack = () => {
this.history.goBack();
};
goForward = () => {
this.history.goForward();
};
}
export const useNavigation = () =>
useClassStore<NavigationStore>(container.get(NavigationStore));
export default NavigationStore;
import React from "react";
import { Switch, Route, Router, Redirect } from "react-router-dom";
import Auth from "./pages/auth";
import Dashboard from "./layouts/Dashboard";
import { observer } from "mobx-react-lite";
import { useNavigation } from "./stores/navigationStore";
import { useUserStore } from "./stores/userStore";
const PrivateRoute: React.FC<{
component: any;
path: string;
}> = observer(({ component: Component, ...rest }) => {
const { isLoggedIn } = useUserStore();
const { history } = useNavigation();
if (!isLoggedIn) {
history.replace("/");
return null;
}
return <Route {...rest} render={(props) => <Component exact {...props} />} />;
});
const Routes = () => {
const { history } = useNavigation();
const { init } = useUserStore();
React.useEffect(() => {
init();
}, []);
return (
<Router history={history}>
<Switch>
<Route path="/" exact render={() => <Auth />} />
<PrivateRoute path="/dashboard" component={() => <Dashboard />} />
</Switch>
</Router>
);
};
export default observer(Routes);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment