AndyD
AndyD

Reputation: 895

Flux/ReactJS - One Store per API endpoint or One Store to all API endpoints?

I'm facing a bit of confusion in the planning of my ReactJS/Flux app. It will be hooking into the WP Api which has the following endpoints:

/api/stores/
/api/posts/
/api/settings/

What would be the best approach from a build perspective? My thoughts currently are to have the following:

API -> ActionCreator -> Store -> ActionCreator -> View(s)

Meaning that in some cases each view will contain change listeners for up to three stores and the potential for a lot of duplicated code.

Another alternative is one actionCreator to many stores, but I am not sure which is the best for scalability.

Can anyone help on this?

Upvotes: 2

Views: 190

Answers (1)

François Richard
François Richard

Reputation: 7045

ActionCreator is not involved between stores and views just between server/store or views/server

API -> ActionCreator -> Store ---binding_eventChange---> View(s) --actionCreator-->request ...etc

For my api I use one store for each endpoint of the api which are one type of data. A view will be indeed binded to many stores (3,4,5stores ...etc) that's why I cut the view in several subviews, each subview is binded to one type of data/store. So I have a big parent view wich render several sub tiny views, it allows to have simple (sub)views easy to read and it also make the code very modular, you can easily make composition of subviews.

Edit: In your example in comment what you want to do is: 1.Loading your view 2.Your view is requesting a type of data 3.your store receive the asked data. 4.Your view, binded to the store, updates using the new data.

I'll write it quickly in pseudo-code:

1.In your view:

componentDidMount() {
   //calling your actioncreator to init the first call to the server
   ActionCreator.requestSomeTypeofData();
   // Set your store listener so your view can update when the data are here
   SomeTypeofDataStore.on('change', handler);
}

handler: function() {
    var data = SomeTypeofDataStore.getAll();
    this.setState({ data:data });
}
  1. In your actionCreator:

    actionCreator.requestSomeTypeofData = function() { MakeAjaxCall({ success: function(data) { Dispatcher.handleViewAction({ actionType:"SomeTypeofData", result: data }); }

    }

  2. Store: when the ajax call is done, new data are dispatched to the store

Basically you are using Dispatcher.register and a switch to select the right action for your store (I let you look at the flux tutorial for that but I guess you know that already). You also bind a 'change' event when you register new data (see tutorial and how they use EventEmitter that's easy). (example here: https://facebook.github.io/flux/docs/todo-list.html#creating-stores)

  1. Your view receive the update event, call the handler register new state and rerender with your new data

I hope it's clear :)

Upvotes: 2

Related Questions