1

I have problem with updating component when remove element from redux state.

my component:

const mapStateToProps = state => ({
  products: state.shoppingBasket.list,
});

const ShoppingBasket = React.createClass({
  propTypes: {
    removeProduct: React.PropTypes.func.isRequired,
    products: React.PropTypes.array,
    open: React.PropTypes.func.isRequired,
  },
  removeFromBasket(index, name) {
    this.props.removeProduct(index);
  },
  render() {
    return (
      <div>
        {this.props.products.map((product, index) => (
              <div key={index}>
                product.name
                <button onClick={() => this.RemoveFromBasket(index)}
              </div>
            );
          )}
      </div>
    );
  },
});

export default connect(mapStateToProps, actions)(ShoppingBasket);

my reducer:

export default function shoppingBasket(
  state = {
    list: [],
  },
  action
) {
  let tmp = [];
  switch (action.type) {
    case SHOPPING_BASKET_ADD:
      return { list: [...state.list, action.payload.product] };
    case SHOPPING_BASKET_REMOVE:
      tmp = state.list;
      tmp.splice(action.payload.index, 1);
      return { list: tmp };
    default:
      return state;
  }
}

When insert element in redux state my component successfuly update, but when i click on button and call removeFromBasket element was remove from redux state but commponent shouldn't update.

1 Answer 1

3

splice doesn't return new array but only mutates array on which it's called so refernce to list property doesn't change. In Redux you must always return new state object (never mutate state) otherwise your component will not updated because internally it performs shallow comparision of current and next properties so if references hasn't changed it considers them equal and prevents component re-render. You can remove item fron an array in a Redux way like this:

   case SHOPPING_BASKET_REMOVE:
      return { list: [
       ...state.list.slice(0, action.payload.index),
       ...state.list.slice(action.payload.index + 1)
      ]
   }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, also work and return { list: state.list.filter((_, i) => i !== action.payload.index) };

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.