0

I have this useEffect hook

useEffect(() => {
    console.log('mark useEffect', compatibleProducts);
    if (Object.keys(compatibleProducts.rims).length === 0
            && Object.keys(compatibleProducts.tires).length === 0) return;

}, [compatibleProducts,...]);

enter image description here

As you can see in the picture the state with the (COMPATIBLE_PRODUCTS) changes at the last line. In the state I check, indeed values are added, but the useEffect hook doesn't trigger again.

Any reason why it does this ?

State before: enter image description here State after: enter image description here

Reducer action: enter image description here

4
  • Is this redux? Can you show us the reducer where you mutate the state? The fact that you see the action running does not mean that you are returning a new state (mutating the current state is wrong). Commented Feb 18, 2021 at 8:49
  • @keul I have edited my question Commented Feb 18, 2021 at 9:02
  • the object identity of your array 'compatibleProducts' stays the same. you can either copy the contents compatibleProducts: [...action.compatibleProducts] or spread it into the deps array useEffect(() => {}, [...compatibleProducts] Commented Feb 18, 2021 at 9:08
  • @Martin good answer but don't you mean the following: useEffect(() => {}, [{...compatibleProducts}] Because useEffect(() => {}, [...compatibleProducts] Gives me the error Type 'CompatibleProductsInterface' must have a '[Symbol.iterator]()' method that returns an iterator.. Even so, it still doesn't work Commented Feb 18, 2021 at 9:12

1 Answer 1

1

You should try in reducer

case TYPE.COMPATIBLE_PRODUCTS.SUCCESS:
            return {
                ...state,
                compatibleProducts: {
                    ...state.compatibleProducts,
                    ...action.compatibleProducts,
                    timespan: + new Date()
                }
            }

in your component

useEffect(() => {
    ...
}, [compatibleProducts.timespan]);
Sign up to request clarification or add additional context in comments.

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.