스터디/코딩애플
리액트 - 로컬 스토리지 : 캐시
sakuraop
2022. 12. 23. 03:52
로컬스토리지
로컬스토리지는 재접속 해도 브라우저에 남아있다.
+세션스토리지는 브라우저를 끄면 휘발된다.
로컬스토리지 다루는 법
localStorage.setItem("key", "value")
키와 값 저장하기
localStorage.getItem("key") // "value"
값 가져오기
localStorage.removeItem("key") // undefined
키 삭제하기
array/object를 저장하려면 JSON으로 변환
let userData = { name: "Amy" };
userData = JSON.stringify(userData)
let userJSONData = localStorage.getItem("userData");
console.log(userJSONData); // {"name":"Amy"} JSON 데이터 가져옴
let userParsedData = JSON.parse(userJSONData);
console.log(userParsedData); // {name: 'Amy'} object로 변환한 데이터 가져옴
let userName = userParsedData.name;
console.log(userName); // Amy 객체의 name 키의 값을 가져옴
로컬스토리지 다루기
1. 로컬스토리지 생성 (이미 있으면 하지 않도록 하기)
useEffect(() => {
if (localStorage.getItem("productId") === null) {
localStorage.setItem("productId", JSON.stringify([]));
}
}, []);
2. 로컬스토리지에서 자료 꺼내기
3. 꺼낸 자료에 데이터 추가하기 (중복이 있다면 추가하지 않기)
4. 로컬 스토리지에 데이터 추가한 자료 넣기
useEffect(() => {
const viewedItem = JSON.parse(localStorage.getItem("productId"));
viewedItem.push(parseInt(params.id));
const viewedItemSet = new Set(viewedItem);
const viewedItemArray = Array.from(viewedItemSet);
localStorage.setItem("productId", JSON.stringify(viewedItemArray));
}, []);