-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAuthContext.js
81 lines (74 loc) · 2.1 KB
/
AuthContext.js
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import React, { useContext, useState, useEffect } from 'react'
import { auth } from '../firebase'
const AuthContext = React.createContext()
//useAuth hook
export function useAuth() {
return useContext(AuthContext)
}
export function AuthProvider({ children }) {
const [currentUser, setCurrentUser] = useState()
const [loading, setLoading] = useState(true)
//create user
function signup(email, password) {
return auth.createUserWithEmailAndPassword(email, password)
}
//login function
function login(email, password) {
return auth.signInWithEmailAndPassword(email, password)
}
//logout function
function logout() {
return auth.signOut()
}
//reset password
function resetPassword(email) {
return auth.sendPasswordResetEmail(email)
}
// Update email
function updateEmail(email) {
return auth.currentUser.updateEmail(email)
}
// Update password
function updatePassword(password) {
return auth.currentUser.updatePassword(password)
}
//delete account
function deleteAccount() {
return auth.currentUser.delete()
}
//update displayname
function updateDisplayName(userName) {
return auth.currentUser.updateProfile({
displayName: userName,
})
}
//useEffect so you only run it when mounting component
useEffect(() => {
//firebase method to set current user
const unsubscribe = auth.onAuthStateChanged(user => {
setCurrentUser(user)
//no loading when there already is a user
setLoading(false)
})
return unsubscribe
}, [])
//Export
const value = {
currentUser,
signup,
login,
logout,
resetPassword,
updateEmail,
updatePassword,
deleteAccount,
updateDisplayName,
}
return (
//value contains all the information you want to provide at authentication
//See above
<AuthContext.Provider value={value}>
{!loading && children}
</AuthContext.Provider>
)
}