javascripthtmlcss

"Log in" button doesn't hide after registration or log in


I want to make the log in button disappear after you're signed into your account, but I can't seem to get it right. I've tried with localStorage and sessionStorage, but neither have worked. What am I doing wrong?

Login:

var objPeople = [{
    username: "#",
    password: "#"
  },
  {
    username: "#",
    password: "#"
  },
  {
    username: "test",
    password: "123"
  }
]

function getInfo() {
  var username = document.getElementById("username").value
  var password = document.getElementById("password").value

  for (var i = 0; i < objPeople.length; i++) {
    if (username == objPeople[i].username && password == objPeople[i].password) {
      console.log(username + "is logged in.")
      window.location.href = "homepage.html"
      localStorage.setItem("signedIn", 1);
    }

  }
  console.log("Username/password is incorrect.")
}

Homepage:

const signedInTrue = localStorage.setItem("signedIn")
if (signedInTrue= 1) {
    document.getElementById("topNav").style.display = "block"
}

Solution

  • First of all, there are some errors in homepage...

    1. Storage#getItem(), not Storage#setItem()

    You want to get the data, aren't you? I think there's just a simple mistake.

    2. Assigning to constant value error

    In this code, you are trying to set the constant value, and also it's like a small error

    What homepage must look like?

    const signedInTrue = localStorage.getItem("signedIn") //getItem(), not setItem()
    if (signedInTrue == 1) { //two equals signs
        document.getElementById("topNav").style.display = "block"
    }
    

    However, there is a lack of information such as:

    Without these information, we can't help you. The only thing is the idea how to make it - once you check if the user is logged, set the button display to none (or visiblity to hidden/collapse).

    Also, if you ask what storage to use, it depends what is the purpose: if you want to keep the login state only when user is on page, use sessionStorage. If you want to keep it for longer, use localStorage instead.