Skip to content

Commit

Permalink
protected route fix when refreshing page
Browse files Browse the repository at this point in the history
  • Loading branch information
OttaviaFeletig committed Jul 1, 2022
1 parent e9d3304 commit 84c12f6
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 21 deletions.
20 changes: 7 additions & 13 deletions src/components/ProtectedRoute.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,10 @@
import React, { useContext } from 'react'
import { Navigate } from 'react-router-dom';
import useIsAuthenticated from '../utils/useIsAuthenticated'
import React, { useContext } from "react";
import { Navigate } from "react-router-dom";
import { AuthContext } from "../context/AuthContext";
function ProtectedRoute({ children }) {
const { user, loading } = useContext(AuthContext);

function ProtectedRoute({children}) {

const isAuthenticated = useIsAuthenticated();

return (
<>
{isAuthenticated ? children : <Navigate to="/login"/>}
</>
)
return loading ? <p>Loading</p> : user ? children : <Navigate to="/login" />;
}

export default ProtectedRoute
export default ProtectedRoute;
8 changes: 6 additions & 2 deletions src/context/AuthContext.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ export const AuthContext = createContext();

export const AuthContextProvider = (props) => {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const redirectTo = useNavigate();

const register = async (email, password) => {
console.log("email + password", email, password);

Expand Down Expand Up @@ -56,8 +56,10 @@ export const AuthContextProvider = (props) => {
if (user) {
// const uid = user.uid;
setUser(user);
setLoading(false);
} else {
setUser(null);
setLoading(false);
}
});
};
Expand All @@ -77,7 +79,9 @@ export const AuthContextProvider = (props) => {
}, []);

return (
<AuthContext.Provider value={{ user, setUser, register, login, logout }}>
<AuthContext.Provider
value={{ user, setUser, register, login, logout, loading }}
>
{props.children}
</AuthContext.Provider>
);
Expand Down
13 changes: 7 additions & 6 deletions src/utils/useIsAuthenticated.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import React, { useContext } from 'react'
import { AuthContext } from '../context/AuthContext'

import React, { useContext } from "react";
import { AuthContext } from "../context/AuthContext";
// ! NOT IN USE
function useIsAuthenticated() {
const { user } = useContext(AuthContext);
const { user } = useContext(AuthContext);

const isAuthenticated = user !== null ? true : false;

const isAuthenticated = user !== null ? true : false;
return isAuthenticated;
}

export default useIsAuthenticated
export default useIsAuthenticated;

0 comments on commit 84c12f6

Please sign in to comment.