DLynnSmith
DLynnSmith

Reputation: 77

React: Redirect to new page from FUNCTION not from COMPONENT (working with React Router)

I have a function running using a setInterval timer. Its purpose is to ask the server if the login/sessionID I have in local storage is still valid. If the session has expired, I want to give an alert and route to the Login page.

I would normally use something like this.props.history.push("/login") to accomplish the redirect. But this cannot be a Component; being run by setInterval, it must be a function. The React-Router history.push option is not available outside of Components, AFAIK. What would be my best alternative?

Here is the setInterval code that happens at Login:

sessionStorage.setItem('mycha_sessionID',returnData.data.sessionID)
let intervalID = setInterval(CheckSession,1*30*1000)
sessionStorage.setItem('intervalID',intervalID)

And the function code that will run every interval:

import {axiosGet} from "./AxiosCalls";
import {ClearSession} from "./ClearSession";

export function CheckSession() {
    // Call Wordpress to see if the current session ID is still valid
    if (sessionStorage.getItem('mycha_sessionID')) {
        axiosGet(sessionStorage.getItem('mycha_base_url')+"/wp-json/mycha/check-session")
            .then(res => {
                if ((false === res.data) || ("" === res.data)) {
                    ClearSession()
                    alert("Your login session has expired.  Please log in again before continuing.")
                    // Redirect to Login here
                }
            })
            .catch(err => alert(err));
    }

    return
}

Upvotes: 1

Views: 378

Answers (1)

Duderino9000
Duderino9000

Reputation: 2597

I may be misunderstanding, but why not just call window.location.href = 'https://www.my-site.com/login'

Upvotes: 1

Related Questions