Created
August 25, 2020 09:53
-
-
Save justinbiebur/a8f590def1e9430ad4e30d99501fc904 to your computer and use it in GitHub Desktop.
a part of the medium article on firebase auth and react-router.
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, {createContext,useState, useEffect} from 'react'; | |
import {auth} from './firebase'; | |
export const AuthContext= createContext({userPresent:false,user:null}) | |
export default function FirebaseAuthContext(props){ | |
let [state,changeState] = useState({ | |
userDataPresent:false, | |
user:null, | |
listener:null | |
}) | |
useEffect(()=>{ | |
if(state.listener==null){ | |
changeState({...state,listener:auth.onAuthStateChanged((user)=>{ | |
if(user) | |
changeState(oldState=>({...oldState,userDataPresent:true,user:user})); | |
else | |
changeState(oldState=>({...oldState,userDataPresent:true,user:null})); | |
})}); | |
} | |
return ()=>{ | |
if(state.listener) | |
state.listener() | |
} | |
},[]) | |
return ( | |
<AuthContext.Provider value={state}> | |
{props.children} | |
</AuthContext.Provider> | |
) | |
} |
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, { useContext } from 'react'; | |
import {AuthContext}from './firebaseAuthContext'; | |
import {Route,Redirect} from 'react-router-dom'; | |
export default function ProtectedRoute(props){ | |
const authValue=useContext(AuthContext) | |
if (authValue.userDataPresent){ | |
if(authValue.user==null){ | |
return(<Redirect to={props.redirectTo}></Redirect>) | |
} | |
else{ | |
return( | |
<Route exact path={props.path}> | |
{props.children} | |
</Route>) | |
} | |
} | |
else{ | |
return null | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment