I want to create a login form and a registration form on a separate page. I'm using useNavigate() and a context to navigate the user to the Main
page when they've been logged in. But the user can't go to the registration page because if (!user) history('/');
doesn't let do it. How can I fix this so that an user can register on the Registration
page and when the user is already logged in then stay on the Main
page? Thank you.
App.js:
function App() {
return (
<div style={{fontFamily: 'Avenir'}}>
<Router>
<AuthProvider>
<Routes>
<Route path="/main" element={<Main/>}/>
<Route path="/" element={<Login/>}/>
</Routes>
</AuthProvider>
<Routes>
<Route path="/registration" element={<Registration/>}/>
</Routes>
</Router>
</div>
);
}
AuthContext.js:
const AuthContext = React.createContext();
export const AuthProvider = ({children}) => {
const [loading, setLoading] = useState(true);
const [user, setUser] = useState(null);
const history = useNavigate();
useEffect(() => {
onAuthStateChanged(app, (user) => {
setUser(user);
setLoading(false);
if (user) history('/main');
if (!user) history('/');
})
}, [user, history]);
const value = {user};
return (
<AuthContext.Provider value={value}>
{!loading && children}
</AuthContext.Provider>
);
}
Login.js:
export function Login() {
//...
return(
//...
<a href="/registration"><h2>Registration</h2></a>
);
}