Search code examples
reactjsreactjs-flux

Maintain focused Item in List under React + Flux architecture


I have one list of items, and I have a div for showing the detail of item as well. For example,

--------------------------------------------
| Items List  |  Selected Item Detail      |
--------------------------------------------
| Item A      |   Item C is selected       |
| Item B      |   Item C is a cool         |
| Item C*     |                            |
| Item D      |                            |
--------------------------------------------

And my components are:

- AppContainer
  - Item List
    - Item
  - Selected Item Detail

The AppContainer has the following stats

  • allItems
  • selectedItemId

Here comes my question: is the implementation correct?

  1. Should I maintain selectedItemId (an integer) in AppContainer, and find the corresponding item by the id when passing selected item to Selected Item Detail?
  2. Or should I keep a selectedItem (an object) as state, and pass it to Selected Item Detail directly?
  3. Should I keep the selectedItem or selectedItemId in Flux's Store? (given I keep the allItems in Store after using Flux in my application.)

Thanks.


Solution

  • As your questions suggest, there are multiple ways to achieve the same thing, so I think it's not a matter of is the implementation correct so much as which implementation makes the most sense.

    Should I maintain selectedItemId (an integer) in AppContainer, and find the corresponding item by the id when passing selected item to Selected Item Detail? Or should I keep a selectedItem (an object) as state, and pass it to Selected Item Detail directly?

    I think in general it's preferable to keep the state as compact as possible and derive data that depends on other data where it's actually needed. There's also the old DRY standard of 'don't repeat yourself.' Since the selected item can be derived from the set of all items and the index, I would store the index rather than an extra copy of the item.

    Should I keep the selectedItem or selectedItemId in Flux's Store? (given I keep the allItems in Store after using Flux in my application.)

    For the same reasons as above, I would store the ID rather than a copy of the item.