Skip to content

Instantly share code, notes, and snippets.

@justinbiebur
Created August 25, 2020 09:53
Show Gist options
  • Save justinbiebur/a8f590def1e9430ad4e30d99501fc904 to your computer and use it in GitHub Desktop.
Save justinbiebur/a8f590def1e9430ad4e30d99501fc904 to your computer and use it in GitHub Desktop.
a part of the medium article on firebase auth and react-router.
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>
)
}
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