I want to keep making my request because whenever I add an item to my cart, the carticon which displays the amount of items in the cart has to update. But this keeps refreshing my session, so when I put this to production you it becomes laggy. I want to solve this by running it maybe once, and not onclick because the components which could be doing this on click, are just not connected with eachother.
export default function Header({ props }) {
const pollingRef = useRef(0);
const [newItemState, setNewItemState] = useState(0);
const [itemsState, setItemsState] = useState(props.cart);
let finalquantity = itemsState.map((item) => item?.quantity || 0);
// console.log(finalquantity);
const updateCartAmount = async () => {
try {
let itemQuantities = itemsState.map((item) => item?.quantity || 0);
let newItemState = itemQuantities.reduce((acc, sum) => acc + sum, 0);
console.log(newItemState);
const response = await axios.get('/cartjson');
setItemsState(response.data);
setNewItemState(newItemState);
} catch (error) {
console.error('Failed to update cart', error);
}
};
useEffect(() => {
pollingRef.current = setInterval(() => {
updateCartAmount();
// console.log('polling');
}, 2000)
return () => {
clearInterval(pollingRef.current)
}
}, []);
Im using Inertia and i found something about UseRemember but i dont really know if thats something what could solve this. I want to update the quantity but NOT the session tokens