Search code examples
reactjsimmutability

React: tell state that class instance has mutated


I have this class:

class MyClass {
  constructor() {
    this.value = 'foo';
  }

  mutate() {
    this.value = 'bar';
  }
}

And a component that has an instance in its state:

let Component = React.createClass({
  getInitialState: function() {
    return {
      element: new Myclass()
    };
  },
  mutateElement: function() {
    this.state.element.mutate();
  }
});

How can I let <Component /> know that this.state.element has mutated and that it needs to re-render?

Using React immutability Helpers won't work as the following syntax is not valid:

mutate() {
  this = update(this, {value: {$set: 'bar'}); 
}

Solution

  • There are two ways to go about this. First is the easy way: this.forceUpdate() But react specifically tells to avoid it as much as possible. But I feel you have a valid use case.

    let Component = React.createClass({ 
        getInitialState: function() { 
            return { element: new Myclass() }; 
        }, 
        mutateElement: function(){ 
            this.state.element.mutate();
            this.forceUpdate();
        } 
    });
    

    But if you want to stick with not using this.forceUpdate() you could have another variable in state and set that.

    let Component = React.createClass({ 
        getInitialState: function() { 
            return { element: new Myclass(),
            hasChanged: false }; 
        }, 
        mutateElement: function(){ 
            this.state.element.mutate();
            this.setState({hasChanged: true});
        } 
    });
    

    This will mutate it and also re-render your component.