Last active
November 29, 2021 18:34
-
-
Save brunokiafuka/f832df8e6c07f1f2e6407a563ea1eb95 to your computer and use it in GitHub Desktop.
Mobx+React-router navigation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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