Skip to content

Commit

Permalink
Create user context
Browse files Browse the repository at this point in the history
  • Loading branch information
german-zarate committed Oct 9, 2020
1 parent abaf273 commit c2a3208
Show file tree
Hide file tree
Showing 5 changed files with 51 additions and 3 deletions.
35 changes: 35 additions & 0 deletions firebase/context.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import React, { useState, useEffect, useContext, createContext } from "react";
import { firebase, auth, db } from "../config/firebase";

const authContext = createContext();
export function AuthProvider({ 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 getCurrentUser = () => {
db.collection("Users")
.doc(auth.currentUser.uid)
.get()
.then((doc) => {
setUser(doc.data());
});
};

useEffect(() => {
const unsubscribe = firebase
.auth()
.onAuthStateChanged(() => getCurrentUser());
return () => unsubscribe();
}, []);

return {
user,
getCurrentUser,
};
}
4 changes: 3 additions & 1 deletion jsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
"paths": {
"@/icons/*": ["components/icons/*"],
"@/styles/*": ["styles/*"],
"@/components/*": ["components/*"]
"@/components/*": ["components/*"],
"@/config/*": ["config/*"],
"@/firebase/*": ["firebase/*"]
}
}
}
8 changes: 7 additions & 1 deletion pages/_app.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import "@/styles/globals.css";

import { AuthProvider } from "../firebase/context";

function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
return (
<AuthProvider>
<Component {...pageProps} />
</AuthProvider>
);
}

export default MyApp;
5 changes: 5 additions & 0 deletions pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import Products from "components/HomeProducts";
import { db } from "config/firebase";
import Layout from "components/Layout";

import { useAuth } from "../firebase/context";

export default function Home() {
db.collection("Users")
.get()
Expand All @@ -19,6 +21,9 @@ export default function Home() {
});
});

const auth = useAuth();
console.log(auth);

return (
<Layout>
<div className={styles.container}>
Expand Down
2 changes: 1 addition & 1 deletion pages/login/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export default function LoginPage() {
auth.onAuthStateChanged(function (user) {
if (user) {
console.log(user);
// router.push("/"); active it later
router.push("/");
}
});

Expand Down

0 comments on commit c2a3208

Please sign in to comment.