denislexic
denislexic

Reputation: 11362

React setState and flux action update

I need a click function to do an update to the store through flux action and also update the state of the component.

Example: I have a form field with data for a story, and a state to say if the modal with the form is open.

// Initial state
return {
    story: this.props.story,
    modalIsOpen: true
}

--

// Click function to close the modal
closeModal: function(e){
    e.preventDefault();
    story.update(newStory)  // <== Flux action to update the story, which then updates this component 
    this.setState({modalIsOpen: false})  // <== To actually close the modal
}

But it seems that whatever I put first runs and not the second one. So if I have story.update(newStory) first it executes that one but not this.setState({modalIsOpen: false}) and vice versa...

Any ideas what I'm doing wrong or how to execute both?

Upvotes: 0

Views: 1089

Answers (2)

Boris Zagoruiko
Boris Zagoruiko

Reputation: 13174

If you're using ES2015 class for creating React component (instead of React.createClass()) you might forget to bind event handler method to component's context. There are several ways to do it easily, here's a good tutorial: http://www.ian-thomas.net/autobinding-react-and-es6-classes/

I prefer using autobind-decorator. With it you should fix your component to something like:

import autobind from "autobind-decorator";

class Foo extends React.Component {

  /* ... */

  @autobind
  closeModal: function(e){
    e.preventDefault();
    story.update(newStory)  // <== Flux action to update the story, which then updates this component 
    this.setState({modalIsOpen: false})  // <== To actually close the modal
  }

}

Upvotes: 1

wintvelt
wintvelt

Reputation: 14101

You should not need the this.setState() after your story.update().
Probably after your action call, your component is re-rendered before the this.setState() is executed. The flow should be:

  • your component calls story.update()
  • store listens to dispatcher and updates
  • store emits change
  • your component listen to change
  • method inside component responding to store update does setState( {modalIsOpen: false} ).

Also, it seems that your story does not need to be in state: your component simply could simply render this.props.story.

Upvotes: 1

Related Questions