first commit
This commit is contained in:
45
src/Context/AuthProvider.js
Normal file
45
src/Context/AuthProvider.js
Normal file
@@ -0,0 +1,45 @@
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { userStateListener } from "../firebase";
|
||||
import { createContext, useState, useEffect } from "react";
|
||||
|
||||
export const AuthContext = createContext({
|
||||
currentUserEmail: undefined,
|
||||
currentUserCreatedAt: undefined
|
||||
});
|
||||
|
||||
export const AuthProvider = ({ children, history }) => {
|
||||
const [currentUser, setCurrentUser] = useState({
|
||||
currentUserEmail: undefined,
|
||||
currentUserCreatedAt: undefined
|
||||
});
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
const unsubscribe = userStateListener((user) => {
|
||||
const token = user?.accessToken;
|
||||
if (token) {
|
||||
window.sessionStorage.setItem("token", token);
|
||||
} else {
|
||||
window.sessionStorage.removeItem("token");
|
||||
}
|
||||
if (!user) {
|
||||
setCurrentUser({
|
||||
currentUserEmail: null,
|
||||
currentUserCreatedAt: undefined
|
||||
});
|
||||
} else {
|
||||
let createdAt = new Date(parseInt(user.metadata.createdAt, 10));
|
||||
if (isNaN(createdAt)) {
|
||||
createdAt = undefined;
|
||||
}
|
||||
setCurrentUser({
|
||||
currentUserEmail: user.email,
|
||||
currentUserCreatedAt: createdAt
|
||||
});
|
||||
}
|
||||
});
|
||||
return unsubscribe;
|
||||
}, [navigate]);
|
||||
|
||||
return <AuthContext.Provider value={currentUser}>{children}</AuthContext.Provider>;
|
||||
};
|
||||
Reference in New Issue
Block a user