'React js go back to previous page after sign in
I am trying to redirect the user back to the previous page after successful login using styled firebase authentication ui. My code for component Login.js doesn't work well to redirect the user to previous page when I use 'history.goBack().'. Below is my code:
firebase.js
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
const firebaseConfig = {...};
const firebaseApp=firebase.initializeApp(firebaseConfig);
const db=firebaseApp.firestore();
const auth=firebase.auth();
// const state=({isSignedIn: false})
const uiConfig=({
signInFlow: "popup",
signInOptions: [
firebase.auth.GoogleAuthProvider.PROVIDER_ID,
firebase.auth.FacebookAuthProvider.PROVIDER_ID,
firebase.auth.TwitterAuthProvider.PROVIDER_ID,
firebase.auth.GithubAuthProvider.PROVIDER_ID,
firebase.auth.EmailAuthProvider.PROVIDER_ID
],callbacks:{
signInSuccessWithAuthResult: () => false,
},
});
export {uiConfig};
in login.js
import React, { useState, useEffect } from 'react';
import { uiConfig } from './firebase';
import { useHistory } from 'react-router-dom/cjs/react-router-dom.min';
import firebase from 'firebase/compat/app';
import StyledFirebaseAuth from 'react-firebaseui/StyledFirebaseAuth'
function Login() {
const history = useHistory ();
const [isSignedIn, setIsSignedIn] = useState(false);
useEffect(() => {
const unregisterAuthObserver = firebase.auth().onAuthStateChanged(user => {
setIsSignedIn(!!user);
});
return () => unregisterAuthObserver(); // Make sure we un-register Firebase observers when the component unmounts.
}, []);
if (!isSignedIn) {
return (
<div className='login'>
<div className='left_login'>
{/* <h1>Wei White Art</h1> */}
<h1>Please sign-in:</h1>
<br />
<StyledFirebaseAuth uiConfig={uiConfig} firebaseAuth={firebase.auth()} />
</div>
<div className='right_login'>
<h1>Wei White Art</h1>
<br />
<img
className='login_logo'
src='../Logo design 7.png' alt='' />
</div>
</div>
);
}
return (
history.goBack()
);}
export default Login;
'history.goBack()' does not direct the user to the previous page. how to direct user to previous page after successful log in?
Solution 1:[1]
You can use useNavigate() like so, instead of the isSignedIn state
const navigate = useNavigate();
const location = useLocation();
const from = location.state?.from?.pathname || "/";
console.log(location);
if (user) {
navigate(from, { replace: true }); //if user logs in, takes user to wherever he could not access first or to homepage
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rittika Dev |
