3

When using React and Flux, it's standard practice to make API calls from actions, and then store the resulting data in a Store class. But who should be responsible for transforming that data after it's been stored?

Example: I've got an EntryStore that keeps hold of objects representing shopping list items. I have a number of filters that I can apply to them (e.g "show only dairy"). I currently have this working by calling EntryActions.filterEntries('dairy'), which the dispatcher then passes to EntryStore where a _filterEntries(tag) method transforms theEntryStore._entries array. Is this considered best practice? Should the action itself transform the list of entries, then pass it to EntryStore to simply save? How dumb should the Store be in this case?

Steven Mercatante
  • 24,757
  • 9
  • 65
  • 109
  • Couldn't you just filter when the view renders? Or use CSS? Seems overkill to use flux's dataflow in this instance, IMHO. I sometimes filter in the store, but only when the data is static and right after the store has received all the data. – GijsjanB Oct 22 '14 at 08:13

1 Answers1

3

Yep, you're right! In Flux, we want to keep the data structure flat, and let any data manipulation occur in the Stores themselves. The data-flow is essentially:

Component --> (actions) --> Dispatcher --> (callback) ---> Stores -----+
Ʌ                                                                      |
|                                                                      V
+-- ("change" event handlers) --------------------- (change events) ---+

Mutation of data has to happen through calling actions from your views/components. The data stores listen on these actions and mutate the data within the store (including filtering, and any other data mutations or logic you may need)

trekforever
  • 3,914
  • 25
  • 29
  • 2
    I'm little hung up on this example. Let's assume no immutable JS for the moment. Say I filter my store to only include dairy. Cool, I now have a dairy-specific store. Now I want to filter it to "meats". If I've changed out the contents of the store, how am I going to filter everything again? – imjared Mar 26 '15 at 20:04
  • Ideally you should be using immutable data structures, since that data flow model aligns well with ideas of Flux and React (Facebook even has a dedicated immutable data structure just for React and Flux: https://facebook.github.io/immutable-js/). Otherwise you would need to filter it on the view via React components (which isn't wrong, but just more data-logic in your view layer). – trekforever Mar 31 '15 at 01:20