서버나 데이터베이스가 없을 경우 데이터를 반영구적으로 저장하는 방법은 localStorage를 사용하는 것이다.
브라우저를 껐다 켜도 정보가 남아있고 안쓰면 직접 지워줘야한다.
이와 다르게 session은 브라우저를 껏다키면 사라진다.
저장하는 방법
localStorage.setItem('name','kim')
출력하는 방법
localStorage.getItem('name')
삭제하는 방법
localStorage.removeItem('name')
데이터는 문자열로만 등록이 가능하다.
그렇기 때문에 array나 object 같은 경우는 JSON.stringify() 와 JSON.parse() 를 이용하면 됨.
최근본상품 기능 구현
localStorage에 상세보기를 눌렀던 상품의 id값을 저장할 것이다.
그러기 위해 localStorage에 key=saw, value=[] 이렇게 빈 배열을 저장해줘야한다.
null값을 만들지 않기 위함이기도 하다.
그리고 아래 코드를 추가해준다.
.
.
const ls = localStorage.getItem("saw");
const lsArr = JSON.parse(ls).reverse();
useEffect(() => {
let arr = JSON.parse(ls);
if (!arr.includes(shoe[0].id)) {
if (arr.length === 5) {
arr.shift();
}
arr.push(shoe[0].id);
} else {
arr = arr.filter((el) => {
return el !== shoe[0].id;
});
arr.push(shoe[0].id);
}
localStorage.setItem("saw", JSON.stringify(arr));
.
.
<div className="col-md-2">
<Saw lsArr={lsArr} shoes={props.shoes}></Saw>
</div>
.
.
function Saw(props) {
const navigate = useNavigate();
return (
<div>
<div>최근본상품</div>
{props.lsArr.map((id, index) => {
const item = props.shoes.find((it, i) => {
return it.id === id;
});
const i = item.id + 1;
return (
<div key={index}>
<img
src={"https://codingapple1.github.io/shop/shoes" + i + ".jpg"}
width="120px;"
title={item.title}
onClick={() => {
navigate(`/detail/${item.id}`);
}}
/>
</div>
);
})}
</div>
);
}
최근본상품은 최대 5개로 하고 중복을 피하기 위해 Set을 이용하는 방법도 있지만 조건식으로 풀어봤다.
className="row" 안에 col-md-5,5,2 이렇게 변경하여 레이아웃을 변경했다.
Saw Component를 만들었고 그 안에 배열의 id값으로 상품을 찾아 상품정보를 return하여 보여주었다.
그리고 이미지를 클릭하면 상세화면으로 이동하게 navigate 함수를 사용했다.
이렇게 localStorage 이용하여 최근본상품을 구현해보았다.