0

I am trying to redirect user to the URL hostUrl+'logout' when they click Yes button from the Are you sure you want to log out? popup dialog. Since my other parts of code is making use of react router, I am wondering if I could make use of the same inside the following function :

 logoutDialogClose = event =>{
    if (event) {
        this.setState({ displayLogoutPopup: false})
        
       
    }        
}

Someone in this post suggested making use of Link but not sure if that applies to my case or not.

Maybe I will need a separate function logoutDialogYes once above testing is done to separate Cancel and Yes clicks from the popup dialog.

My complete code is below:

const hostUrl = properties.baseUrlUI

class Main extends Component {
    constructor() {
        super();
        this.state = {
          
         
            isAuthenticated: false,
            displayLogoutPopup: false,
            
        };
        this.logoutDialogOpen = this.logoutDialogOpen.bind(this)        
        this.logoutDialogClose = this.logoutDialogClose.bind(this)

    }

    componentDidMount() {
     //some stuff here  
     }

    loadDropDownObjects() {
          // some axios call to store info in session storage
    }

    logoutDialogOpen = event =>{
        if (event) {
            this.setState({ displayLogoutPopup: true})
                      
        }        
    }

    logoutDialogClose = event =>{
        if (event) {
            this.setState({ displayLogoutPopup: false})
            /* <Link to="/">
                <i className="fa fa-sign-out pull-right"></i> 
                Log Out
          </Link> */
          
           /*  console.log("Testing host URL");
            console.log(hostUrl);
            axios.delete(hostUrl+'logout')
            //axios.get(hostUrl+'logout') 
            .then(response => {
                console.log("Reaching inside the response of logoutDialogClose function and printing the response below:");
                console.log(response);
                //keeping the setState outside until we test it on dev server
                //this.setState({ displayLogoutPopup: false})
            })
            .catch (error => {
                console.log("logout error", error);
            }) */
           
        }        
    }
    
    render() {
       
        const logoutDialog = this.state.displayLogoutPopup ? (
            <div className="popup popup--icon -question js_question-popup"
                 id={this.state.displayLogoutPopup ? 'popup--visible' : ''}>
                <div className="popup__background"></div>
                <div className="popup__content">
                    <h3 className="popup__content__title">
                        Are you sure you want to log out?
                    </h3>
                    <p>
                        <button className="button button_accept" onClick={this.logoutDialogClose}>Yes</button>
                        <button className="button button--warning" onClick={this.logoutDialogClose}>Cancel</button>
                    </p>
                </div>
            </div>
        ) : null

        return (
            
            <div>
            {
                this.state.isAuthenticated ? (
                    <BrowserRouter basename={process.env.REACT_APP_ROUTER_BASE || ''}>
                        <div>
                            <div className="header">
                                <div className="header-logo">
                                <img src="images/logo.jpg"/>
                                <span>DATA</span>
                                </div>

                                <div className="logout_sec">
                                <div className="logout_icon">
                                    <a href="javascript:void(0)" onClick={this.logoutDialogOpen}> <FontAwesomeIcon
                                        style={{fontSize: '1.5em'}} icon={faSignOutAlt}/></a>
                                </div>
                                </div>                                

                                <ul className="header-list">
                                <li>
                                    <NavLink exact to="/">
                                        Home
                                    </NavLink>
                                </li>
                                <li>
                                    <NavLink to="/myprojects">My Projects</NavLink>
                                </li>
                                <li>
                                    <NavLink to="/myassets">My Assets</NavLink>
                                </li>
                              
                                <li>
                                    <NavLink to="/datadownload">DataSet Download</NavLink>
                                </li>
                                <li>
                                    <NavLink to="/assetbrowser">Asset Browser</NavLink>
                                </li>
                            </ul>



                                {/* Popup COde start */}

                                {logoutDialog}
                                {/* Popup code End */}
                            </div>

                            <div id="forNotification"></div>
                            <div>
                                <Switch>
                                    <Route exact path="/" component={Home}/>
                                    <Route path="/myprojects"
                                           render={(props) =>
                                               <div>
                                                   <Projects {...props}/>
                                               </div>
                                           }
                                    />
                                    
                                  
                                    <Route exact path="/project" component={ProjectView}/>
                                    <Route exact path="/datadownload" component={DataDownload}/>
                                    <Route exact path="/assetbrowser" component={AssetBrowser}/>
                                    <Route exact path="/datarequest" component={DataRequest}/>
                                    <Route path='/404' component={NotFoundPage}/>
                                    <Redirect to="/404"/>
                                </Switch>
                            </div>
                        </div>
                    </BrowserRouter>
                ) : null
            }
            </div>
        );
    }
}

export default Main;
Tan
  • 1,433
  • 5
  • 27
  • 47
  • You can use react router history to just push to the page you want - https://reactrouter.com/web/api/history – Sowam Jul 07 '21 at 15:14
  • Does this answer your question? https://stackoverflow.com/questions/59402649/how-can-i-use-history-pushpath-in-react-router-5-1-2-in-stateful-component – Shuvo Jul 07 '21 at 15:35
  • I keep getting `"export 'useHistory' was not found in 'react-router-dom'` while using the useHistory hook. My `react-router-dom` version is `4.3.1.`. Looks like this is not supported in this version. Is there a way to achieve what I am looking for without using this hook? I am trying not to go through upgrading `react-router-dom` version if possible. Also my react version is `16.4.2`. for the hook, I believe it's 16.8 needed based on my online research – Tan Jul 07 '21 at 15:45

1 Answers1

1

Try adding this import:

import {withRouter} from 'react-router-dom';

Change the export statement to:

export default withRouter(Main);

Then, you should be able to access the history object inside Main through this.props.history. For example:

logoutDialogClose = event =>{
    if (event) {
        this.setState({ displayLogoutPopup: false})
        
       this.props.history.replace(`/some/path`);
       // OR
       this.props.history.push(`/some/path`);
    }        
}

Edit:

Try replacing the export statement with this:

const MainWithRouter = withRouter(Main);

const MainWrapper = props => (
    <BrowserRouter basename={process.env.REACT_APP_ROUTER_BASE || ''}>
        <MainWithRouter {...props} />
    </BrowserRouter>
);

export default MainWrapper;
Neal Burns
  • 839
  • 4
  • 5
  • Tried the above. Getting `Uncaught Invariant Violation: You should not use or withRouter() outside a ` error. This is happening when I am using `export default withRouter(Main);`. If I keep it as `export default Main;` with other changes you mentioned, it doesn't throws any error. Any idea what could be wrong? – Tan Jul 07 '21 at 19:54
  • Are you saying that it completely works if you remove withRouter()? – Neal Burns Jul 07 '21 at 19:55
  • I don't get an error when I just use `export default Main;` at the bottom. However, it doesn't work with this. I believe I will have to fix the error that I am seeing with `export default withRouter(Main);` first. My `react-router-dom` and `react-router` version are `4.3.1` if this helps. Thanks ! – Tan Jul 07 '21 at 19:59
  • Try removing `` out of `Main` and changing the export statement to `export default withRouter(Main)` – Neal Burns Jul 07 '21 at 20:03
  • 1
    I removed ` ` and ` ` and did as you mentioned with export and now getting this error as shown in the image link here : https://i.stack.imgur.com/Ta38Y.png – Tan Jul 07 '21 at 20:12
  • Thanks. I tested your code and there were no errors this time. However, when I click `Yes` button to test the `logoutDialogClose` function, it is taking me to this path ` ` instead of the one defined inside `this.props.history.replace(`/some/path`);` or ` this.props.history.push(`/some/path`);`. Any idea what might be causing this? – Tan Jul 07 '21 at 21:34
  • What is `hostUrl+'logout'`? Is that an ajax call or a client-side path? – Neal Burns Jul 07 '21 at 22:00
  • `hostUrl` is `https://myserver.com/project/`. This is the URL which is used by the user to log into the system. If I have to log them out, I need to take them to `https://myserver.com/project/logout`. This basically ends their session. It's not an Ajax call. Please let me know if I can answer any questions. Thanks! – Tan Jul 08 '21 at 13:16
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/234674/discussion-between-tan-and-neal-burns). – Tan Jul 08 '21 at 19:49