Reputation: 548
How can useEffect
detect the change in an array's object's property
without knowing the state
array size because items may be added dynamically
state
Just for example if changing the price property useEffect
won't invoke, price will be the same next time (after - localStorage.getItem
)
(In my app I change it dynamically in a different way this is for example).
const checkUseEffectLocalS = () => {
array[0]['Price'] = '12';
setItemsArray(array);
};
return (
<>
<div>
<button
onClick={() => checkUseEffectLocalS()}>
Check
</button>
</>
);
useEffect(() => {
localStorage.setItem(userItems, JSON.stringify(array));
}, [array.map((item) => item.price)]); //Tried this way also but it didn't worked
Niether
useEffect(() => {
localStorage.setItem(userItems, JSON.stringify(array));
}, [array]); // won't work
The array structure
array([
{
id: 1,
productName: 'Vitamin',
price: '10$',
},
{
id: 2,
productName: 'Powder',
price: '26$',
},
{
id: 3,
productName: 'Multivitamin',
price: '17.5$',
},
]);
Before asking I checked very similar question but with no real answer - stackoverflow
Thanks in advance.
Upvotes: 4
Views: 3734
Reputation: 258
Without using useEffect
const checkUseEffectLocalS = () => {
let arr= [...array]
arr[0]['Price'] = '12';
localStorage.setItem(userItems, JSON.stringify(arr))
setItemsArray(prev=>arr);
};
return (
<>
<div>
<button
onClick={() => checkUseEffectLocalS()}>
Check
</button>
</>
)
By using useEffect
useEffect(() => {
localStorage.setItem(userItems, JSON.stringify(array))
}, [JSON.stringify(array)])
Upvotes: 4