Martijn van der Maas
Martijn van der Maas

Reputation: 51

React Reflux: Correct way to initiate stores and update dependent components

I'm just starting with Reflux and React. I've watched several React/flux tutorials/videos, but I haven't found the correct way to set up my application with Reflux/React and React Router:

Imagine I have the following url: localhost:9000/projects/1/roles/2/action/3. Based on the url I should be able to trace back the state of the application. So in my Route handler I have the following set-up:

App.cjsx

routes = (
  <Route handler={AppWrapper}>
    <Route name="project" ...
    <Route name="action" handler={Action} path="/project/:project_id/roles/:role_id/actions/:action_id" />
  </Route>
)

In this case, {Action} is the component that should receive data from the store. This Action-component listens to the ActionStore to receive data:

componentWillMount: () ->
  actionStore.listen (actions) =>
    @setState({ actions: actions })

According to several tutorials, I should initiate my store in the bootstrap, so I added the following line in my App.cjsx:

ActionStore     = require('./stores/ActionStore.cjsx') 

The actionstore has the following initiate method:

actionStore = Reflux.createStore 
    init: () ->
        $.ajax
          url: 'rest/mock' + period.name + '.json'
          dataType: 'json'
          success: (actions) =>
            @trigger(actions)
          error: (xhr, status, err) ->
            console.log('err:' + err)
        return  

module.exports = actionStore

My problem is that the flow in the application is not correct. The flow is now:

  1. Create and initiate ActionStore
  2. Store initiates and loads actions from server
  3. Initiate Action component (add listener to store)

So the actionstore has already received the data, after that the component is initialized, so it never gets the trigger from the actionstore. How do I set this up with React Router and Reflux the correct way?

Upvotes: 1

Views: 2593

Answers (1)

Alexandre Kirszenberg
Alexandre Kirszenberg

Reputation: 36418

Your ActionStore could keep the actions data in a local state variable, and let components access it via actionStore.getState().

Thus, in your components, you could simply do

getInitialState: () ->
  actionStore.getState()

componentWillMount: () ->
  actionStore.listen () =>
    @setState(actionStore.getState())

And your store would look like

actionStore = Reflux.createStore 
    init: () ->
        @state = {};

        $.ajax
          url: 'rest/mock' + period.name + '.json'
          dataType: 'json'
          success: (actions) =>
            @state = { actions }
            @trigger()
          error: (xhr, status, err) ->
            console.log('err:' + err)
        return

    getState: () ->
        @state

module.exports = actionStore

Upvotes: 0

Related Questions