0

I'm currently experiencing problems with getting ImmutableJS and React to work properly. This is not using Redux, therefore I am updating state within the component.

The problem is after I update state, my getter properties are missing on the next rerender causing an Error. Why does setState strip these methods away?

Am I not using ImmutableJS correctly? Is ImmutableJS only intended to be with Redux?

const AssociateRoleLocationStateFactory = RecordFactory<AssociateRoleLocationState>({
  isEditing: false
})

export default class IAssociateRoleLocation extends React.Component {
  constructor(props) {
    super(props)

    this.state = new AssociateRoleLocationStateFactory({
      isEditing: false
    })

    // `this.state` has `.get` method to retrieve properties
    console.log(`initial state:`, this.state) // Record {_map: Map} 
  }

  toggleEditing() {
    let nextState = this.state.set('isEditing', !this.state.get('isEditing'))

    // `nextState` has `.get` method to retrieve properties
    console.log(`next state:`, nextState) // Record {_map: Map}

    this.setState(nextState)
  }

  render() {
    console.log(this.state) // {_map: Map} // Its missing `.get` method on second render
    let isEditing = this.state.get('isEditing')

    return (
      <div className="site-single-column">
        {isEditing ? (
          <div>
            Is Editing!!
          </div>
        ) : (
          <button style={{ alignSelf: 'center' }} onClick={this.toggleEditing}>
              Toggle
            </button>
        )}
      </div>
    )
  }
}

1 Answer 1

2

Currently, React only supports plain js object as the state. You can wrap whatever you want in another key/value layer like

constructor(props) {
  super(props);
  this.state = {
    payload: new AssociateRoleLocationStateFactory({
      isEditing: false
    })
  }
}

There are discussions around this going on like this: https://github.com/facebook/react/issues/3303

But before that, stay pure.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.