Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflux trigger won't work without a delay in init

I use Reflux, and normally I'm triggering after I made an ajax call, and it works well. For testing purposes I didn't need ajax call and I noticed that trigger won't work unless I give a min 5ms timeout. Here are working and not working example.

Not working example:

window.threadStore = Reflux.createStore
  init: ->
    @state = @getInitialState()
    @fetchThreads()
  getInitialState: ->
    loaded: false
    threads: []
  fetchThreads: ->
    # ajax call for not Testing, and just trigger for Testing
    @state.threads = FakeData.threads(20)
    @state.loaded = true
    @trigger(@state) # This will NOT work!

This will work:

window.threadStore = Reflux.createStore
  init: ->
    @state = @getInitialState()
    @fetchThreads()
  getInitialState: ->
    loaded: false
    threads: []
  fetchThreads: ->
    # ajax call for not Testing, and just trigger for Testing
    @state.threads = FakeData.threads(20)
    @state.loaded = true
    setTimeout( =>
      @trigger(@state) # This WILL work!
    , 500)

Can you explain why doesn't it work without a delay and should it? Is it a bug or something I don't understand.

like image 757
Mïchael Makaröv Avatar asked Mar 27 '15 19:03

Mïchael Makaröv


1 Answers

This is because the components get the empty array from getInitialState and it happens after the trigger was invoked.

init is called when the store instance is created which means the trigger in fetchThreads gets invoked immediately before a component was mounted. When the listening Component later gets mounted, it gets the empty array from the store on getInitialState instead.

I'd suggest the following change:

window.threadStore = Reflux.createStore
  init: ->
    @state =
      loaded: false
      threads: []
    @fetchThreads()
  getInitialState: ->
    @state # TODO: State should be cloned for sake of concurrency
  fetchThreads: ->
    # NOTE: Assign a new state for the sake of concurrency
    @state = 
      loaded: true
      threads: FakeData.threads(20)
    @trigger(@state) # This will SHOULD work now ;-)
like image 132
Spoike Avatar answered Oct 16 '22 03:10

Spoike