-
-
Notifications
You must be signed in to change notification settings - Fork 116
/
netlifyAuthContext.tsx
63 lines (49 loc) · 1.53 KB
/
netlifyAuthContext.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
56
57
58
59
60
61
62
63
import React, { createContext, useState, useEffect, ReactNode } from "react";
import netlifyIdentity from "netlify-identity-widget";
import { AuthContextType } from "./authContextType";
const NetlifyAuthContext = createContext<AuthContextType>({
user: null,
login: () => {},
logout: () => {},
authReady: false
});
export const NetlifyAuthContextProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
const [user, setUser] = useState<netlifyIdentity.User | null>(null);
const [authReady, setAuthReady] = useState(false);
useEffect(() => {
const handleLogin = (user: netlifyIdentity.User) => {
setUser(user);
netlifyIdentity.close();
};
const handleLogout = () => {
setUser(null);
};
const handleInit = (user: netlifyIdentity.User | null) => {
setUser(user);
setAuthReady(true);
};
netlifyIdentity.on("login", handleLogin);
netlifyIdentity.on("logout", handleLogout);
netlifyIdentity.on("init", handleInit);
// init netlify identity connection
netlifyIdentity.init();
return () => {
netlifyIdentity.off("login", handleLogin);
netlifyIdentity.off("logout", handleLogout);
};
}, []);
const login = () => {
netlifyIdentity.open();
};
const logout = () => {
netlifyIdentity.logout();
};
const contextValue: AuthContextType = {
user,
login,
logout,
authReady
};
return <NetlifyAuthContext.Provider value={contextValue} >{children}</NetlifyAuthContext.Provider>;
};
export default NetlifyAuthContext;