Cassiopea
Cassiopea

Reputation: 275

React useEffect detect changes in an array inside the object

I am trying to recall an API based on a state change, using useEffect hook. However, my useEffect can't detect changes made to the 'type' array. I tried using use-deep-compare-effect library, but it also couldn't detect a change.

How I can detect changes to my state?

Any help would be very much appreciated!

const [values, setValues] = useState({
        query: '',
        type: ["Tender & Auction", "Merger & Acquisition","Policy & Regulation", "Project Update", "Other"]
    })

 /// Re-run a query, after we check a filter
    useEffect(() => {
          searchAPI(values);
      }, [values]);

I am changing the values like this:

 const handleChange = (newValues) => {
        console.log(newValues)
        setValues({ ...values, type: newValues})
   };

Upvotes: 0

Views: 6092

Answers (2)

Woohaik
Woohaik

Reputation: 1354

Specifying the scope

useEffect(() => {
    searchAPI(values);
}, [values,values.type]);

Upvotes: 1

SoGoddamnUgly
SoGoddamnUgly

Reputation: 766

This is a simple way of doing comparison without causing an infinite loop:

useEffect(() => {
    searchAPI(values);
}, [JSON.stringify(values)]);

or if you only need to track type property:

useEffect(() => {
    searchAPI(values);
}, [JSON.stringify(values.type)]);

Upvotes: 4

Related Questions