Skip to content

Instantly share code, notes, and snippets.

@NavizDev
Created April 14, 2020 14:30
Show Gist options
  • Save NavizDev/d9666b99224fc57be78cd58716d270d7 to your computer and use it in GitHub Desktop.
Save NavizDev/d9666b99224fc57be78cd58716d270d7 to your computer and use it in GitHub Desktop.
hook para manejar firebase en toda la app
import React, { useState, useEffect, useContext, createContext } from "react";
import firebase from "firebase/app";
import "firebase/auth";
import firebaseConfig from "../firebase/firebaseConfig";
if (firebase.apps.length === 0) {
firebase.initializeApp(firebaseConfig);
}
const authContext = createContext();
export function ProvideAuth({ children }) {
const auth = useProvideAuth();
return <authContext.Provider value={auth}>{children}</authContext.Provider>;
}
export const useAuth = () => {
return useContext(authContext);
};
function useProvideAuth() {
const [user, setUser] = useState(null);
const signin = (email, password) => {
return firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then((response) => {
setUser(response.user);
return response.user;
});
};
const signup = (email, password) => {
return firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then((response) => {
setUser(response.user);
return response.user;
});
};
const signout = () => {
return firebase
.auth()
.signOut()
.then(() => {
setUser(false);
});
};
useEffect(() => {
const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
if (user) {
setUser(user);
} else {
setUser(false);
}
});
// Cleanup subscription on unmount
return () => unsubscribe();
}, []);
return {
user,
signin,
signup,
signout,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment