forked from philpalmieri/nextjs-with-firebase-main
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
31 lines (28 loc) · 933 Bytes
/
auth.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
import React, { useState, useEffect, useContext, createContext } from "react";
import nookies from "nookies";
import firebaseClient from "./firebaseClient";
import firebase from "firebase/app";
import "firebase/auth";
const AuthContext = createContext({});
export const AuthProvider = ({ children }) => {
firebaseClient();
const [user, setUser] = useState(null);
useEffect(() => {
return firebase.auth().onIdTokenChanged(async (user) => {
console.log("auth changed");
console.log(user ? user.id : "Nothing");
if (!user) {
setUser(null);
nookies.set(undefined, "token", "", {});
return;
}
const token = await user.getIdToken();
setUser(user);
nookies.set(undefined, "token", token, {});
});
}, []);
return (
<AuthContext.Provider value={{ user }}>{children}</AuthContext.Provider>
);
};
export const useAuth = () => useContext(AuthContext);