Ada
Ada

Reputation: 569

React component does not update with the change in redux state

I have a cart data in this form

const cart = {
  '1': {
    id: '1',
    image: '/rice.jpg',
    price: 32,
    product: 'Yellow Corn',
    quantity: 2,
  },
  '2': {
    id: '2',
    image: '/rice.jpg',
    price: 400,
    product: 'Beans',
    quantity: 5,
  },

  '3': {
    id: '3',
    image: '/rice.jpg',
    price: 32,
    product: 'Banana',
    quantity: 1,
  },
};

In the reducer file I have a function removeItem that is being consumed by the reducer

const removeItem = (items, id) => {
  items[id] && delete items[id];
  return items;
};

case REMOVE_ITEM: {
  const { cart } = state;
  const {
    payload: { id },
  } = action;

  return {
    ...state,
    cart: removeItem(cart, id),
  };
}

In the component I am using this handleRemove() to handle the deletion

handleRemove = id => {
  const {
    actions: { removeItem },
  } = this.props;
  const payload = { id };
  removeItem(payload);
};

Now in the redux developer tool, the change is working effectively but the component view is not updating.

Upvotes: 1

Views: 961

Answers (3)

Anuja
Anuja

Reputation: 1038

Do not mutate redux state, redux does not perform a deep diff check in your objects, when you do not mutate and create new objects, it is automatically detected as a different object, because its plain old js objects.

this would be good for further reading : immutable-update-patterns

so your removeItem method should be,

const removeItem = (items, id) => {
    let {[id]: remove, ...rest} = items
    return rest;
}

You can also use a library to do this, such as dot-prop-immutable , which has set, remove, merge methods to do relevant operations without mutating the object.

Upvotes: 1

mabhijith95a10
mabhijith95a10

Reputation: 436

Change removeItem function to below code

const removeItem = (items, id) => {
    items[id] && delete items[id];
    return {...items};
};

This is because component gets change only if reference changes. You can refer this link for more explanation

Upvotes: 3

marcodt89
marcodt89

Reputation: 411

You need to create a copy of the cart, as otherwise React won't detect the change, because it does reference comparison and you return the same object. Try to do the removeItem() in this way.

const removeItem = (items, id) => {
    let itemsClone = [...items]; // Copies all items into a brand new array
    itemsClone [id] && delete itemsClone [id]; // You perform the delete on the clone
    return itemsClone ; // you return the clone
};

Upvotes: 1

Related Questions