os
use
state type State position,
of nissor of nature and size of an
lens used image when abfect
placedat distance
equal to its focal
length
Rear View in Vehicles conles me
meiros
To obselle minute conllex
parts of watch lens
repailer
8
Page No.
Answers
Answer:
I am trying to setState of items on render using a function call and then watch the items state for changes to cause re-render if they change. Passing a reference to the object keys as per the suggested answer does not seem to change anything. I am trying to do this using the hook useEffect(). getCart() is an function to retrieve data from localStorage. Code:
const [items, setItems] = useState([]);
useEffect(() => {
setItems(getCart());
}, [items]);
I am getting an error "Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render."
I understand how I am causing an infinite loop by effectively changing the items state on render and then this causes a re-render and so on. How would I get around this, is this possible using useEffect? Thanks.
Edit: Code that edits the localStorage
export const updateItem = (productId, count) => {
let cart = [];
if (typeof window !== 'undefined') {
if (localStorage.getItem('cart')) {
cart = JSON.parse(localStorage.getItem('cart'));
}
cart.map((product, index) => {
if (product._id === productId) {
cart[index].count = count;
}
})
localStorage.setItem('cart', JSON.stringify(cart))