1

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
}
4
  • 1
    I may be misunderstanding, but why not just call window.location.href = 'https://www.my-site.com/login' Commented Dec 30, 2019 at 21:11
  • Thank you, Barryman. I was defaulting to a React-ish way of dealing with the issue, not thinking of normal JS techniques. I just tested, and this did seem to get past part of my problem. I will test further to be sure I didn't create a new issue to replace it. :-) Commented Dec 30, 2019 at 21:24
  • @Barryman9000, this just worked fine for me. Thank you very much. I did end up using window.location.pathname = '/login' instead of .href. That lets the same code work whether running in my test or production environments without having to specify the base domain of the url. :-) Commented Dec 31, 2019 at 13:07
  • Great! I added an answer so you can mark this post as answered. Commented Dec 31, 2019 at 17:16

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.