Skip to content

Instantly share code, notes, and snippets.

@harsh317
Created June 25, 2022 05:08
Show Gist options
  • Save harsh317/7ceda6c0715a21814a43713cb9f930f1 to your computer and use it in GitHub Desktop.
Save harsh317/7ceda6c0715a21814a43713cb9f930f1 to your computer and use it in GitHub Desktop.
Our Context API file with basic Functions
import React, { useContext, useState, useEffect } from "react";
import {
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
onAuthStateChanged,
signOut,
GoogleAuthProvider,
signInWithPopup,
} from "firebase/auth";
import { doc, setDoc } from "firebase/firestore";
import { db, auth } from "../Config/FirebaseConfig";
const AuthContext = React.createContext();
export const useAuth = () => {
const auth = useContext(AuthContext);
return { ...auth, isAuthenticated: auth.CurrentUser != null };
};
export function AuthProvider({ children }) {
const [CurrentUser, setCurrentUser] = useState();
const [loading, setloading] = useState(true);
useEffect(() => {
const unsuscribe = onAuthStateChanged(auth, (user) => {
console.log(user);
setCurrentUser(user);
setloading(false);
});
return unsuscribe;
}, []);
const SignupUser = (email, password, name) => {
return createUserWithEmailAndPassword(auth, email, password).then(
(resp) => {
if (resp.user) {
CreateFireStoreUser(
resp.user,
name,
"https://cdn-icons-png.flaticon.com/512/149/149071.png"
);
}
}
);
};
const CreateFireStoreUser = (user, name, profileImage) => {
const UsersRef = doc(db, "Users", user.uid);
setDoc(UsersRef, {
name: name,
profileImage: profileImage,
initials: name[0] + name[name.length - 1],
Suscribers: [],
}).then(() => {
console.log("added User");
});
};
const LogInUser = (email, password) => {
return signInWithEmailAndPassword(auth, email, password);
};
const SignInWithGoogle = () => {
const provider = new GoogleAuthProvider();
return signInWithPopup(auth, provider);
};
const logout = () => {
return signOut(auth);
};
const value = {
CurrentUser,
SignupUser,
LogInUser,
logout,
ResetPassword,
CreateFireStoreUser,
};
return (
<AuthContext.Provider value={value}>
{!loading && children}
</AuthContext.Provider>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment