0

I am trying to update the state of an object in an array in React using Immutability Helpers.

  handleChange = (itemInput, itemNum = null) => event => {
    this.setState({
      rows: update(this.state.rows, {
        itemNum: {[itemInput]: {$set: event.target.value}},
      })
    });
  }

I get an error "Uncaught TypeError: Cannot read property 'update' of undefined". The reason is itemNum is undefined and I can't figure out why(I know it is undefined since if I replace it with 1, for example, the code works. This is probably some scope issue :/ Thanks for any suggestions on how to fix that!

Just to clarify that the variables are all defined and I can console.log them before the this.setState.

update comes from https://reactjs.org/docs/update.html . I used the example under "Nested collections" where they have hardcoded the value 2, and in my case, it has to be itemNum

Basically, what I am trying to do is

this.state.rows[itemNum][itemInput] = event.target.value

but I guess React makes it a bit complicated for me...

In the constructor I have

this.handleChange = this.handleChange.bind(this);

And I call the onChange with onChange={this.handleChange("searchType", i)}

9
  • 2
    Why you have used currying concept here ? () => () => Commented Jun 5, 2019 at 15:29
  • 1
    What is update? Commented Jun 5, 2019 at 15:33
  • 1
    Can you show the update function? Commented Jun 5, 2019 at 15:33
  • 1
    Do you mind sharing whole class ? Commented Jun 5, 2019 at 15:42
  • 1
    As per documentation itemNum has to be index and itemInput has to be array, just wanna look on that part Commented Jun 5, 2019 at 15:43

1 Answer 1

1
handleChange = (itemInput, itemNum = null) => event => {
    this.setState({
        rows: update(this.state.rows, {
            [itemNum]: {[itemInput]: {$set: event.target.value}},
        })
    });
};
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.