Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useEffect Hook - how to detect the change of an object's property in a state array

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

  • in this particular case the "price" property in one of the objects
    The array is a 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.

like image 833
ExtraSun Avatar asked Oct 16 '25 21:10

ExtraSun


1 Answers

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)])
like image 86
Alwani Anis Avatar answered Oct 19 '25 12:10

Alwani Anis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!