만약 local Storage에 찾는 정보가 없다면?
콘솔창에
localStorage.getItem("username")
// null 출력
이렇게 유저정보의 유무를 알아볼 수 있다.
if (savedUsername === null) {
//show the form
} else {
//show the greetings
}
위와 같은 방식으로
'유저정보가 없다면 form을 보여주고, 있다면 인사말을 보여주는'
코드를 작성해줄 수 있다.
반복되는 string, 즉 문자열들은 대문자 변수로 지정해놓으면 좋다.
오타났을때도 바로 알 수 있기 때문.
const HIDDEN_CLASSNAME = "hidden";
const USERNAME_KEY = "username";
function onLoginSubmit(event) {
event.preventDefault();
loginForm.classList.add(HIDDEN_CLASSNAME);
const username = loginInput.value;
localStorage.setItem(USERNAME_KEY, username);
greeting.innerText = `Hello ${username}`;
loginForm.classList.remove(HIDDEN_CLASSNAME);
}
loginForm.addEventListener("submit", onLoginSubmit);
const savedUsername = localStorage.getItem(USERNAME_KEY);
요렇게.
if (savedUsername === null) {
//show the form
loginForm.classList.remove(HIDDEN_CLASSNAME);
loginForm.addEventListener("submit", onLoginSubmit);
} else {
//show the greetings
paintGreetings(savedUsername);
}
function paintGreetings(username) {
greeting.classList.remove(HIDDEN_CLASSNAME);
greeting.innerText = `Hello ${username}`;
}
paintGreetings 라는 함수는
greeting.classList.remove(HIDDEN_CLASSNAME);
greeting.innerText = `Hello ${username}`;
이 2번 반복되어서 하나의 함수로 만들어 놓은 것.