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.
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 ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With