Reflux trigger won't work without a delay in init
Asked Answered
J

1

6

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.

Johnsonian answered 27/3, 2015 at 19:24 Comment(0)
M
5

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 ;-)
Menefee answered 1/4, 2015 at 6:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.