๋กœ์ปฌ์Šคํ† ๋ฆฌ์ง€

์ฝ˜์†”์— ํ…Œ์ŠคํŠธํ•ด๋ณด๋ฉด ๋Œ€์ถฉ ๋Š๋‚Œ์ด ์˜ด.

image.png

localStorage.setItem("hs", true);

Applicationํƒญ์— Local Storage๋กœ ํ™•์ธํ•ด๋ณด๋ฉด,:

image.png

setItemํ–ˆ๋˜ ๊ฐ’์ด ๋“ค์–ด๊ฐ€ ์žˆ๋Š”๊ฑธ ํ™•์ธํ•  ์ˆ˜ ์žˆ์Œ.

๋ฐ˜๋Œ€๋กœ ์ž…๋ ฅ๋œ ๊ฐ’์„ ๊ฐ€์ ธ์˜ค๋ ค๋ฉด getItem์ด๋ผ๋Š” ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.

image.png

getItem === null ?

๊ทธ๋ ‡๋‹ค๋ฉด localStorage.getItem()์˜ ๊ฒฐ๊ณผ๊ฐ’์ด NULL์ด๋ผ๋Š” ๊ฒƒ์€ ์–ด๋–ค ๊ฑธ ์˜๋ฏธํ• ๊นŒ?

NULL์ด๋ผ๋ฉด ๊ฐ’์ด ์—†๋Š” ๊ฒƒ.
์ฆ‰, ์•„์ง ์œ ์ €๊ฐ€ input์— ์•„๋ฌด ๊ฐ’๋„ ๋„ฃ์ง€ ์•Š์•˜๋‹ค๋Š” ์†Œ๋ฆฌ๋‹ค.
์œ ์ €๊ฐ€ ์ด๋ฆ„์„ ์ž…๋ ฅํ•˜๋ฉด ํผ์„ ์ˆจ๊ธฐ๊ณ  ์ž…๋ ฅํ•œ ๊ฐ’์„ ๋…ธ์ถœ์‹œํ‚ค๋Š” ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด๋ณด์ž.:

const form = document.querySelector(".js-form"),
    input = form.querySelector("input"),
    greeting = document.querySelector(".js-greetings");

const USER_LS = "currentUser",
    SHOWING_CN = "showing";

function handleSubmit(event){
    event.preventDefault();             // form์ด submit๋  ๋•Œ reloadํ•˜๋Š” ํ˜„์ƒ ๋ง‰๊ธฐ    
    const currentValue = input.value;
    paintGreeting(currentValue);
}
function askForName(){
    form.classList.add(SHOWING_CN);
    form.addEventListener("submit", handleSubmit);
}

function paintGreeting(text){
    form.classList.remove(SHOWING_CN);
    greeting.classList.add(SHOWING_CN);
    greeting.innerText = `Hello ${text}`;
}

function loadName(){
    const currentUser = localStorage.getItem(USER_LS);
    if(currentUser === null){
        askForName();
    }else{
        paintGreeting(currentUser);
    }
}

function init(){
    loadName();
}

init();

image.png

image.png

์•„์ง ๋ถ€์กฑํ•˜๋‹ค

์ƒˆ๋กœ๊ณ ์นจ์„ ๋ˆ„๋ฅด๋ฉด ์ •๋ณด๊ฐ€ ์‚ฌ๋ผ์ง„๋‹ค.
๋งˆ์ง€๋ง‰ function์„ ๋งŒ๋“ค์–ด๋ณด์ž.

function saveName(name){
    localStorage.setItem(USER_LS, name);
}

image.png

๊ฐ’์ด ๋กœ์ปฌ์Šคํ† ๋ฆฌ์ง€์— ์ €์žฅ์ด ๋˜๋ฉด์„œ ์ƒˆ๋กœ๊ณ ์นจ์„ ํ•ด๋„
๊ฐ’์ด ์‚ฌ๋ผ์ง€์ง€ ์•Š๊ณ  ๋‚จ์•„์žˆ๋Š” ๊ฒƒ์„ ํ™•์ธ ํ•  ์ˆ˜ ์žˆ๋‹ค.