Reputation: 649
I have a footer where i am setting the cookie upon language selection. So when the user returns to the website again, then with the help of cookie i am redirecting the user to the page locale url. I am checking the cookie value in componentDidMount() lifecycle hook. But when the user redirects it again reads the cookie and the redirection goes in an infinite loop. How can i make the redirection occur only once. I am using es-cookie npm package for the cookie mechanism.
Here is my code written in the lifecycle hook.
Update:
If the URL consists of /en-us/aboutus. It returns the condition as true and redirects indefinitely.
componentDidMount() {
const { ariaLabels } = this.props;
this.props.initializeApp(ariaLabels.currentLanguageName);
var currentLanguagePath = getCookie('language_url');
// Redirect if location doesn't match with cookie language_url
let locale = window.location.href.substring(window.location.href.lastIndexOf('/') + 1);
if(locale.endsWith(".html")) {
locale = locale.slice(0,-5);
}
if(locale.endsWith("/")) {
locale = locale.slice(0, -1);
}
if(locale !== currentLanguagePath && currentLanguagePath !== undefined) {
window.location.href = "/" + currentLanguagePath;
}
}
Upvotes: 0
Views: 489
Reputation: 3721
Before redirecting you should check that the current page isn't already using the expected language prefix, so for example
// Assuming currentLanguagePath value looks like 'en-us'
if(!window.location.pathname.startsWith('/' + currentLanguagePath)) {
...
}
Upvotes: 1
Reputation: 9002
Add a check to determine whether the user is already on the correct route:
if (
currentLanguageName &&
currentLanguagePath &&
window.location.href != `/${currentLanguagePath}`
) {
this.props.initializeApp(currentLanguageName);
window.location.href = "/" + currentLanguagePath;
}
Upvotes: 0
Reputation: 2885
Check that currentLanguageName
from props is same as currentLanguageName
from cookie. If they same, you don't need to redirect, else - redirect.
Upvotes: 0
Reputation: 94
if (getCookie("firstVisit") != "true") {
document.cookie = "firstVisit=true";
location.href="Your_New_URL";
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length,c.length);
}
}
return "";
}
I hope this will help you on restricting infinite redirection.
Upvotes: 0