Created
April 14, 2020 14:30
-
-
Save NavizDev/d9666b99224fc57be78cd58716d270d7 to your computer and use it in GitHub Desktop.
hook para manejar firebase en toda la app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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