Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use Redux in this example? [closed]

Tags:

reactjs

redux

So far, Redux hasn't made my life easier. Every time I add a component, I seem to unnecessarily create three files (action, constants, reducer) and think harder than necessary. But I believe there must be a clear advantage of using Redux that I am blind to. Let me take you to the following example.

enter image description here

Expected behavior:

The user can choose multiple items and add them to a shopping cart (POST to backend).

JQuery

This is what I naturally resort to, but I feel like I am doing it wrong if I use plain jQuery. Should I feel this way?

$(function() {
  $(".item").click(function(event) {
    $(event.target).toggleClass("selected");
  }

  $("button.submit").click(function() {
    var selectedItems = $(".item.selected");
    var itemIds = $.map(selectedItems, function(item) { return $(item).data("id") });
    $.post(some_url, {itemsToAdd: itemIds});
});

In React

I would do something like following:

ItemsContainer
  state: selectedItems
  functions: addItem, removeItem, saveCart

Item
  state: isSelected
  props: addItem, removeItem

In Redux

How can I do the same more easily? Maybe I shouldn't store selectedItems as a state inside ItemsContainer and inside a globalState?

like image 895
Maximus S Avatar asked Feb 27 '16 20:02

Maximus S


1 Answers

I don't think it's entirely necessary to create a reducer or action for each component. The reducer and its related actions should be based much more on themes within your data.

The problem may be the example is a bit too small to justify Redux's advantages. Redux aims to address issues of scale. Whereas if this were the entire app I don't see any reason why jQuery wouldn't suffice. People often complain about the "boilerplate" involved with Redux and similar Flux implementations, but its true value is revealed after your app becomes more complex.

To answer your question, I would have a single "Items" reducer and actions with anything related to "Items" and their interactions. Items state tree would have a key like isSelected that would be an array of unique identifiers.

The container itself should pass down "isSelected" as props not as state. I try to avoid having any internal state within components. The state should just continually be updated in a complete loop and passed down as props through your container. I would have a mapStateToProps function in my container that would facilitate this design pattern.

I think this example particularly influenced a lot of my design patterns: http://redux.js.org/docs/advanced/ExampleRedditAPI.html

like image 51
Matthew K. Turner Avatar answered Sep 28 '22 02:09

Matthew K. Turner