2

The scenario is that there is an object state with an array in it. I want useEffect to be executed when values are added or changed in it. I tried a few solutions but none of them worked.

       const [filter, setFilter] = useState({})
       const firstUpdate = useRef(true);

    useEffect(() => {
    
        console.log("Filter Updated")
        if (firstUpdate.current) return firstUpdate.current = false;
          
        // API  Calls Here
        
      }, [filter])


const handler = (categoryName, categoryId) => {
    let x = filter;
    x.categoryIDs = [categoryId];
    setFilter(x)
    
  }
Brian Thompson
  • 13,263
  • 4
  • 23
  • 43
  • I believe what you want is to set dependecy as `[filter.categoryIDs]` rather than `[filter]` – Ethan Doh Apr 06 '22 at 19:22
  • @EthanDoh I tried that as well didn't work, also I don't think this will be ideal for my use case since I will have a large number of arrays in this state. – Faqahat Fareed Apr 06 '22 at 19:23
  • Yeah, for cases like that, I do create a new state for the array. – Ethan Doh Apr 06 '22 at 19:56
  • [Why can't I directly modify a component's state, really?](https://stackoverflow.com/q/37755997/1218980) – Emile Bergeron Apr 06 '22 at 20:05
  • Hi, I've got the same problem and I solve it with this tutorial: https://dev.to/stephane/how-to-make-sure-useeffect-catches-array-changes-fm3. You just have to change [filter] in your useState by [JSON.stringify(filter)] – xXx_Ninj4_Kill3r_xXx Jun 12 '22 at 06:40

1 Answers1

1

React compares by reference. You simply modify a property of an object and use that in the new state, this wont work.

Try setFilter({...x}).

Istvan Tabanyi
  • 743
  • 5
  • 12