dsuryd / dotNetify-react-template

Real-time React SPA template using dotNetify.
https://dotnetify.net/react
Apache License 2.0
203 stars 57 forks source link

Dispatched state change not reflecting immediately #22

Closed sachin27sharma closed 6 years ago

sachin27sharma commented 6 years ago

Hi, When i dispatch one of my state, the change doesn't get completed until the function ends. On the next function call the state (this.state.SelectedItem) reflects the data i dispatched earlier. Is there any way round it, or do i need to set a timeout for the call to complete so state is correct? this.dispatch = state => this.vm.$dispatch(state);

handleEdit(selectedItem) { this.dispatch({ SelectedItem: selectedItem }); let currentItem = this.state.SelectedItem; }

MrFoxPro commented 6 years ago

Hello. Can you give code example, please? I mean both client and server side

sachin27sharma commented 6 years ago

Here item is one of the items from the collection being looped , the presenter.

handleEdit(selectedItem) { this.props.onEdit(selectedItem); }

FloatingActionButton onClick={this.handleEdit.bind(this, item)} zDepth={0} mini={true} iconStyle={styles.buttonIconStyle} style={{ backgroundColor: pink500 }} >

                  </FloatingActionButton

In the container, handleEdit(selectedItem) { this.dispatch({ SelectedItem: selectedItem }); --- want to do other action after state has been updated, basically calling another components passing updated state as props. ---- }

sachin27sharma commented 6 years ago

ignore missing tags in FloatingActionButton, as it was not appearing here in the issue, so removed it.

dsuryd commented 6 years ago

React setState function which was used by vm.$dispatch is asynchronous, you need to code accordingly.

sachin27sharma commented 6 years ago

Anyway i can capture when dispatch finishes specific state change?

dsuryd commented 6 years ago

Use the appropriate React lifecycle hook to get notified of the state change.

dsuryd commented 6 years ago

Sorry, correction: vm.$dispatch only dispatches data to the back-end and does not call React setState. If the back-end view model responds to that dispatch by setting another property value, that change will get propagated back to the client and then setState will get called, which in turn will cause the component to re-render. When this happens, you can use the React lifecycle hook for updating to listen to the state change, or handle it inside the render method itself.

sachin27sharma commented 6 years ago

Thanks. Handling in componentWillUpdate now. Looks better.