Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Tags
more
Archives
Today
Total
관리 메뉴

우당탕탕 개발일지

LocalStorage 본문

Front-end/React

LocalStorage

YUDENG 2023. 5. 4. 00:10

localStorage는 웹 브라우저에서 제공하는 클라이언트 측 데이터 저장소이다.

웹 페이지에서 사용하는 데이터를 로컬에 저장하고, 나중에 사용할 수 있다. 저장해야할 데이터가 별로 중요하지 않거나 잃어버려도 상관없는 데이터일 때 효율적이다. 세션이 유지되는 동안에만 데이터를 저장할 수 있는 sessionStorage와 달리, localStorage는 데이터가 영구적으로 보존된다.

 

  • setItem() - ( key, value ) 데이터 저장
localStorage.setItem("key", "value");
  • getItem() - 데이터 가져오기
const value = localStorage.getItem("key");
console.log(value);
  • removeItem() - 데이터 삭제하기
localStorage.removeItem("key");
  • clear() - 모든 데이터 삭제하기
localStorage.clear();

 

< localStorage에 객체 저장 방법>

 

다음과 같이 Team 객체를 localStorage에 저장하였더니 오류가 발생하였다.

const onApply = () => {
    const newTeam = {
      name: team,
      description: description,
      member: member,
    };
    //데이터 저장하기
    localStorage.setItem(team, JSON.stringify(newTeam));
    
    //데이터 가져오기
    const savedTeam = JSON.parse(localStorage.getItem(team));
  };

localStorage에 객체를 저장하려면 객체를 JSON 문자열로 변환하여 저장해야 하고, 이를 위해서는 JSON.stringify() 함수를 사용해야 한다. 또한, 데이터를 가져올 때는 localStorage에서 team이라는 키로 가져오고 JSON.parse() 함수를 사용하여 객체로 변환한다.

 

728x90

'Front-end > React' 카테고리의 다른 글

컴포넌트 export  (0) 2023.05.07
리액트 함수 선언  (0) 2023.05.04
JSX  (0) 2023.04.19
리액트를 사용하는 이유  (0) 2023.04.17
Styled Component  (0) 2023.04.16