4

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.

2
  • you want to handle the state change ? Commented Aug 11, 2021 at 16:05
  • @AlwaniAnis Yes sure Commented Aug 11, 2021 at 16:08

1 Answer 1

4

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)])
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, but is there a way with useEffect ? because I don't think I wanna use localStorage.setItem twice, each in a different component. It will get complicated I think
Yes I will edit my answer to add the other way.
You can look at my previous question to see how I change the property -stackoverflow.com/questions/68743359/…
I think my answer works very well with your situation, to handle objects change you should convert it to json string , that is it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.