Refactor: separate authMachine from React (#5110)
* Create a global appMachine
* Strip authMachine of side-effects
* Replace react-bound authMachine use with XState actor use
* Fix import goof
* Register auth commands directly!
* @lf94 feedback: conver `AuthNavigationHandler` to `useAuthNavigation`
* Uh, fix signing out thank you @lf94
* Fix tsc
* A snapshot a day keeps the bugs away! 📷🐛 (OS: namespace-profile-ubuntu-8-cores)
* Revert "A snapshot a day keeps the bugs away! 📷🐛 (OS: namespace-profile-ubuntu-8-cores)"
This reverts commit 8dc50b6a26
.
---------
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
This commit is contained in:
29
src/hooks/useAuthNavigation.tsx
Normal file
29
src/hooks/useAuthNavigation.tsx
Normal file
@ -0,0 +1,29 @@
|
||||
import { PATHS } from 'lib/paths'
|
||||
import { useAuthState } from 'machines/appMachine'
|
||||
import { useEffect } from 'react'
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
|
||||
/**
|
||||
* A simple hook that listens to the auth state of the app and navigates
|
||||
* accordingly.
|
||||
*/
|
||||
export function useAuthNavigation() {
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const authState = useAuthState()
|
||||
|
||||
// Subscribe to the auth state of the app and navigate accordingly.
|
||||
useEffect(() => {
|
||||
if (
|
||||
authState.matches('loggedIn') &&
|
||||
location.pathname.includes(PATHS.SIGN_IN)
|
||||
) {
|
||||
navigate(PATHS.INDEX)
|
||||
} else if (
|
||||
authState.matches('loggedOut') &&
|
||||
!location.pathname.includes(PATHS.SIGN_IN)
|
||||
) {
|
||||
navigate(PATHS.SIGN_IN)
|
||||
}
|
||||
}, [authState])
|
||||
}
|
Reference in New Issue
Block a user