John Davidson

javascript - Cookie value reverts back to previous value after changing

0 comments
Message:


I have this custom pligin that im using in order to save the user's language preferences. I store it as a cookie like so:


<?php

add_filter( 'init', 'aws_set_language_cookie', 999 );
function aws_set_language_cookie() {
global $TRP_LANGUAGE;
if ( isset( $TRP_LANGUAGE ) ) {
$result = setcookie( 'language', $TRP_LANGUAGE, time() + ( 30 * DAY_IN_SECONDS ), "/", "" , true, true );
}
}

?>

Now if you take a look at the website https://ugrandchurch.com/ open cookies in inspect element after switching to Spanish.
You will see that a cookie by the name of "language" created which holds the value of "es_ES" is saved but it changes to "en_EN" after 3 seconds.


How can I make sure that the value of Spanish "es_ES" is kept instead of being taken overriten by "en_EN".


The WordPress language plugin used here is by the name of TranslatePress



My Answer:
javascript
function setLanguageCookie(language) {
document.cookie = `language=${language}; expires=Fri, 31 Dec 9999 23:59:59 GMT`;
}

function getLanguageCookie() {
const cookieValue = document.cookie
.split('; ')
.find(row => row.startsWith('language='))
.split('=')[1];

return cookieValue;
}

// Example usage
setLanguageCookie('en');
console.log(getLanguageCookie()); // Output: en


_When I change the language using the `setLanguageCookie` function, the cookie value is updated correctly. However, when I refresh the page or navigate to a different page, the cookie value reverts back to its previous value. This is because the cookie is being overwritten by a previous value stored in the browser._

_To fix this issue, you can add a check in the `getLanguageCookie` function to see if the cookie value has been updated during the current session. If it has, return the updated value. Otherwise, return the value stored in the cookie:_

javascript
function getLanguageCookie() {
const updatedLanguage = sessionStorage.getItem('updatedLanguage');

if (updatedLanguage) {
return updatedLanguage;
} else {
const cookieValue = document.cookie
.split('; ')
.find(row => row.startsWith('language='))
.split('=')[1];

return cookieValue;
}
}

function setLanguageCookie(language) {
document.cookie = `language=${language}; expires=Fri, 31 Dec 9999 23:59:59 GMT`;
sessionStorage.setItem('updatedLanguage', language);
}

// Example usage
setLanguageCookie('fr');
console.log(getLanguageCookie()); // Output: fr


_By storing the updated language value in `sessionStorage`, you can ensure that the correct language preference is maintained throughout the user's session, even if the cookie value is overwritten by a previous value._

Rate this post

4 of 5 based on 3598 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us