Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React useEffect doesn't trigger when array in an object state changes

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)
    
  }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading