amal
amal

Reputation: 321

Component re-render when state is an object of objects

I have multiple redux forms on one page. I was able to create different forms using the form attribute when rendering the component.

<ItemDetail form={itemName} />

But I am using the redux store to maintain state for my component. I am creating the redux store dynamically somehow like this:

const currentState = { ...state };
currentState[action.itemName].itemHash = 'fetching';
currentState[action.itemName].itemType = '';
return currentState;

The problem is when I update any property of this object, the component does not re-render.

If I do:

const currentState = { ...state };
currentState[action.itemName]={};
currentState[action.itemName].itemHash = 'fetched';

it re-renders the component correctly. But if I simply do:

const currentState = { ...state };
currentState[action.itemName].itemHash = 'fetching';

it does not re-render it.

Though there is a workaround to deep clone the item object or the same way shown above. But not sure if this is a good way to do so or if we can do it in a cleaner way.

Any help is appreciated!

Upvotes: 0

Views: 671

Answers (1)

Stundji
Stundji

Reputation: 864

Your component is not re-rendering because React will do a shallow comparison of the state. It does this by iterating on the keys of the state being compared and returning true when the values of a key in each object are not strictly equal.

In your case you need to create a new object for your currentState[action.itemName] properties:

    const currentState = { ...state };

    currentState[action.itemName] = {
      ...currentState[action.itemName],
      itemHash = 'fetching',
      itemType = '';
    };

    return currentState;

Upvotes: 1

Related Questions