0

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})
   };
3
  • 2
    Add your code, where you are changing the values Commented Nov 2, 2021 at 12:46
  • Thanks @sojin, added the changes logic, I can see that state changed in my console. Commented Nov 2, 2021 at 12:58
  • 3
    setValues({ ...values, type: [...newValues]}). do this Commented Nov 2, 2021 at 13:08

2 Answers 2

4

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

4 Comments

Thank you @SoGoddamnUgly, I've used JSON.stringify(values.type) and it worked!
Please, never go with this way. It’s an anti pattern.
@LongNguyen what should I use instead?
Did you try with sojin solution? Can you add the way you call handle change to get more help?
1

Specifying the scope

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

Comments

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.