Ad

Resetting State Causing Issues With React Mixin

- 1 answer

In my React component I'm using the MediaMixin to apply classes based on media queries. Here's a simplified example:

R.createClass({
  mixins: [MediaMixin],

  render: function () {
    var mediaquery = this.state.media;

    return (
      <Component responsive={mediaquery.small}>
        <input value={this.state.formInput1} >
        <input value={this.state.formInput2} >
        <input value={this.state.formInput3} >
      </Compontent>
    )
  }
});

In the above, {mediaquery.small} returns true or false depending on viewport size.

The component also has an initial state used to set some values for a form in the component.

getInitialState: function () {
  return {
    formInput1: '',
    formInput2: '',
    formInput3: null
  };
},

When the form is submitted/saved, or the form is cancelled, in order to reset the form we use:

_cancel: function () {
  this.setState(this.getInitialState());
}

This causes issues with the mixin however, as it removes the state property containing the mixin's mediaquery.

The solution I'm using now involves resetting the state properties related to the form manually, like:

_cancel: function () {
  this.setState({
    allowanceType: '',
    allowanceAmount: '',
    allowanceDocument: null
  });
}

Question - How can I reset the state and keep the mixin state properties (without manually resetting each form state property)?

Ad

Answer

You can use this.

_cancel: function () {
    var newState = this.getInitialState();
    newState.media = this.state.media;
    this.setState(newState);
}

Remember, that you should treat current state as immutable (just for info).

Ad
source: stackoverflow.com
Ad