-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNonAuthedScreens.tsx
55 lines (52 loc) · 2.25 KB
/
NonAuthedScreens.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { useEffect } from "react"
import { Switch, Route } from "react-router-dom"
import { LoginScreen } from "./LoginScreen"
import { SignUpScreen } from "./SignUpScreen"
import { ErrorScreen } from "./ErrorScreen"
import { useAuth } from "../../context"
import { client, getUser, createUserSnapshotListener } from "../../firebase"
import styles from "./NonAuthedScreens.module.css"
import { DeleteScreen } from "./DeleteScreen"
/**
* Component that renders all non authed routes, which mainly include the login and sign up pages
*
* Handles logic to redirect a user to the authed routes if a successful login occurs
*/
export function NonAuthedScreens() {
const { setCurrentUser } = useAuth()
useEffect(() => {
// This onAuthStateChanged function calls the passed function whenever someone successfully signs up or logs in.
// This also maintains login persistence, allowing a user to stay signed after multiple sessions.
const unsubscribe = client.auth().onAuthStateChanged(async (user) => {
if (user) {
try {
const userObject = await getUser(user.uid)
setCurrentUser(userObject)
} catch (error) {
// User hasn't been created in firebase yet, wait until it is by binding a snapshot listener to the ref
// where it should exist
const firestoreUnsub = createUserSnapshotListener(user.uid, (newUser) => {
if (newUser) {
firestoreUnsub()
setCurrentUser(newUser)
}
})
}
}
})
return () => unsubscribe()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
return (
<div className={styles.container}>
<main className={styles.window}>
<Switch>
<Route exact path="/" component={LoginScreen} />
<Route path="/signup" component={SignUpScreen} />
<Route path="/error" component={ErrorScreen} />
<Route path="/delete" component={DeleteScreen} />
</Switch>
</main>
</div>
)
}