Reputation: 1855
For making the customized Private Router with respect to currentUser
as given below the code:
AuthContext.js:
import React, {useState, useEffect, useContext} from 'react';
import {auth} from '../Database/Firebase';
const AuthContext = React.createContext();
const useAuth = () => {
return useContext(AuthContext);
}
const AuthProvider = (props) =>{
const [currentUser, setCurrentUser] = useState({});
const signup = (email, password) =>{
return auth.createUserWithEmailAndPassword(email, password);
}
const login = (email, password) =>{
return auth.signInWithEmailAndPassword(email, password);
}
const logout =() =>{
return auth.signOut();
}
useEffect(() =>{
const unscubscribe = auth.onAuthStateChanged((user) =>{
setCurrentUser(user);
});
return unscubscribe;
}, []);
return (
<AuthContext.Provider value={{currentUser, signup, login, logout}}>
{props.children}
</AuthContext.Provider>
);
}
export { AuthProvider, useAuth};
PrivateRoute.js:
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import {useAuth} from "../UserAuthentication/AuthContext";
const PrivateRoute = ({component: Component, ...rest}) => {
const {currentUser} = useAuth();
return (
<Route
{...rest}
render = {(props) =>{
return currentUser ? (<Component {...props} />) : (<Redirect to='/login' />)
}} >
</Route>
);
}
export default PrivateRoute;
Concern on the attached file to show the error:
Note: I am tried to find this error but I should solved it and I think I can do it with the help of stackoverflow members.
Now, I have declare the const {currentUser} = useAuth();
as objects and which is from AuthContext.js
file with the same name. But why it's showed the error, I don't know.
Upvotes: 0
Views: 1051
Reputation: 7388
You need to use the AuthProvider
before you can use useAuth
. Othervise the context value for it will be undefined
and you will get the error as you see it.
Upvotes: 1