Yuehai
Yuehai

Reputation: 1243

Updating state with immutability helper update

I want to update my state with the immutability-helper function update (https://github.com/kolodny/immutability-helper)

state = {
    field: '',
    items: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6']
  };

addElementToList() {
 const i = this.state.items.length;
 const newState = ()=> {
  update(this.state,
    {
      items: {
        $push: [
          {
            [i]: this.state.field
          }
        ]
      }
     }
   )
 };
 this.setState = newState;
}

Unfortunately, I get the following error when the function is executed.

Uncaught TypeError: (0 , _immutabilityHelper.update) is not a function

What have I missed,any thoughts about this?

Upvotes: 1

Views: 2417

Answers (1)

Pineda
Pineda

Reputation: 7593

I know the OP asked for an answer about using this 3rd party library but the original code snippet for this library produced code with an aesthetic that is similar to callback-hell: specifically the use of a lot of nested braces and curly braces.

As a result I just wanted to weigh in on how to achieve the same unmutated state using JavaScript's Array.prototype.concat instead.

You may find that the following approaches are cleaner and more succinct.

Using Array.prototype.concat:

addElementToList() {
  const i = this.state.items.length;
  const   newState = ()=> { 
    items: this.state.items.concat([this.state.field]);
  }
  this.setState = newState;
}

Using ES6 spread syntax:

addElementToList() {
  const i = this.state.items.length;
  const   newState = ()=> { 
    items: [...this.state.items, this.state.field];
  }
  this.setState = newState;
}

Original OP code snippet for comparison:

it uses immutability helper library (https://github.com/kolodny/immutability-helper)

addElementToList() {
  const i = this.state.items.length;
  const newState = ()=> {
    update(this.state,
      {
         items: {
           $push: [
              {
                 [i]: this.state.field
              }
           ]
        }
      }
    )
  };
  this.setState = newState;
}

Upvotes: 2

Related Questions