I'm trying to set the id
property of a state object based on the id
attribute of the button I clicked, and then append it into a state array and then store it in the localstorage. but there are weird things happening in my code:
when I clicked the 1st button, the
console.log
shows theid
value of the 1st button (5) but the state object were still emptythen I clicked on the 2nd button, the
console.log
shows theid
value of the 2nd button (12) but the state object now contains the value from the 1st button (5)then I called the 3rd button, the
console.log
shows theid
value of the 3rd button (100) but the state object contains the value of the 2nd button (12)why are the
Button
s still look like a regular/default button even though I already added thereact-bootstrap
dependency, imported theButton
component, and applied thevariant="link"
in theButton
?
here's my code (and the codesandbox)
import { useState, useEffect } from "react";
import { Button } from "react-bootstrap";
export default function App() {
const [cartList, setCartList] = useState([]);
const [cartItem, setCartItem] = useState({});
useEffect(() => {
let localCart = localStorage.getItem("cartList") || "[]";
console.log("localcart", localCart);
if (localCart) {
localCart = JSON.parse(localCart);
}
setCartList(localCart);
}, []);
const handleClick = (e, item) => {
e.preventDefault();
const arr = e.target.id.split("-");
const selectID = arr[1];
console.log("selectID", selectID);
setCartItem({ ...cartItem, id: selectID });
console.log("cartItem", cartItem);
let itemIndex = -1;
console.log("cartlist", cartList);
for (let i = 0; i < cartList.length; i++) {
if (cartItem && selectID === cartList[i].id) {
itemIndex = i;
}
}
if (itemIndex < 0) {
console.log("added to cartList on index", itemIndex, cartItem);
setCartList([...cartList, cartItem]);
localStorage.setItem("cartList", JSON.stringify(cartList));
}
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<Button
variant="link"
id="item-5"
onClick={(e) => handleClick(e, cartItem)}
>
item no.5
</Button>
<Button
variant="link"
id="item-12"
onClick={(e) => handleClick(e, cartItem)}
>
item no.12
</Button>
<Button
variant="link"
id="item-100"
onClick={(e) => handleClick(e, cartItem)}
>
item no.100
</Button>
<div>
{cartList.length > 0 ? (
cartList.map((item, index) => <div key={index}>{item.id}</div>)
) : (
<div>there is no data here</div>
)}
</div>
</div>
);
}