When a user is signed in, the user can goto route /profile and visit profile page.
<Route exact path={`${path}/profile`}
component={UserProfilePage}
/>
Whis is this component:
import { Switch, Route, useHistory, useRouteMatch } from 'react-router-dom';
import UserProfile from "../components/Profile/UserProfile";
import PrivateRoute from '../components/Auth/PrivateRoute';
const UserProfilePage = () => {
const { path } = useRouteMatch();
console.log(path)
return (
<Switch>
<PrivateRoute path={`${path}`} component={UserProfile} exact/>
</Switch>
)
}
export default UserProfilePage;
This is my private route:
import React, { useContext } from "react";
import { Route, Redirect, useRouteMatch, useLocation } from "react-router-dom";
import AuthFBContext from "../../store/auth-contextFB";
import LangContext from "../../store/lang-context";
export default function PrivateRoute({ component: Component, ...rest }) {
const authFBCtx = useContext(AuthFBContext);
const langCxt = useContext(LangContext);
const { path } = useRouteMatch();
return (
<Route
{...rest}
render={props => {
return authFBCtx.currentUser ?
<Component {...props} /> : <Redirect to={`/${langCxt.lang}/auth/signin`} />
}}
></Route>
);
};
When I goto this page via Link component without reload of the tab, it works fine. but when the browswer is reloaded even with the user authenticated, it redirects to sign in page.
Why is this?
Here is my providers:
useEffect(() => {
onAuthStateChanged(auth, (user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
setCurrentUser(user);
console.log('currentuser:');
console.log(currentUser);
dBCtx.getUserData1(user.uid)
.then((result)=>{
if(result === false) {
console.log('creating a user profile for' + user.uid)
dBCtx.createUser(user.displayName, user.email, user.uid);
}
})
.catch(err => { console.log(err) })
// ...
} else {
console.log('not logged in')
}
});
}, [currentUser])
const contextValue = {
currentUser,
login,
googleLogin,
...
};
return (
<AuthFBContext.Provider value={contextValue}>
{props.children}
</AuthFBContext.Provider>
);
};
export default AuthFBContext;