Reflux trigger will not work without delay in init

I use Reflux, and usually I run after I made an ajax call, and it works well. For testing, I did not need an ajax call, and I noticed that the trigger will not work if I do not give a minimum timeout of 5 ms. Here is a working and not working example.

Example does not 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 @trigger(@state) # This will NOT work! 

code>

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) 

code>

Can you explain why it does not work without delay and should it? Is this a mistake or something I don’t understand.

+6
source share
1 answer

This is because components get an empty array from getInitialState , and this happens after calling trigger .

init is called when the repository instance is created, which means that the trigger in fetchThreads is called immediately before the component is installed. When the listener is later installed, it gets an empty array from the store on getInitialState .

I would 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 ;-) 
+5
source

Source: https://habr.com/ru/post/984338/


All Articles