Noé
Noé

Reputation: 325

Issues accessing localStorage with JavaScript

I'm trying to run a function when body loads, that will check if the user is logged in, and if not redirect them to the login page. Here is the login function :

function login() {
  var mail = document.getElementById('mail').value; //get values
  var psw = document.getElementById('psw').value; //get values
  localStorage.setItem('logged_in', true); //specify that user is logged in
  localStorage.setItem('mail', mail); //store mail
  window.location.replace('pages/home.html'); //redirect to home page
}

And the function to check if the user is logged in :


function check_logged_in() {
  const logged_in = localStorage.getItem('logged_in');
  if (logged_in == null) { //check if user is logged in
    alert('You are not logged in, you are about to be redirected. '); //alert user
    window.location.replace("../index.html"); //redirect to login page
  }
}

The problem is that even if the login function run before, I am redirected. I think that the localStorage resets on each redirection. If that is the problem, do you know the way to prevent this, or if it isn't the problem, do you know what it might be?

Upvotes: 0

Views: 203

Answers (1)

Menas
Menas

Reputation: 1269

Based on the documentation a localStorage item can either be null (when it's empty) or a string. It does not store any other data types.

The expression

localStorage.setItem("logged_in", true);

Does not save a boolean value to the localStorage item. instead, it saves the string value "true"

Upvotes: 1

Related Questions