ImpoUserC
ImpoUserC

Reputation: 619

Update of a specific property in the list of objects

I have a list of dataArray objects

I want to associate TextInput with a specific object in this list.

Every change of text must also change the dataArray in state

How to do it correctly? The code below does not work

export default class MyClass extends Component {
  constructor(props) {
    super(props);

    this.state = {
      dataArray: this.props.dataArray
    };
  }

  _renderContent = section => {
    let arrayIdx = this.state.dataArray.findIndex(
      x => x.title == section.title
    );
    return (
      <TextInput
        value={this.state.dataArray[arrayIdx].content}
        onChangeText={con =>
          this.setState({
            dataArray: update(this.state.dataArray, {
              arrayIdx: { content: { $set: con } }
            })
          })
        }
      />
    );
  };

  render() {
    return (
      <Container>
        <Content padder>
          <Accordion
            dataArray={this.state.dataArray}
            renderContent={this._renderContent}
          />
        </Content>
      </Container>
    );
  }
}

Upvotes: 3

Views: 89

Answers (1)

MrCode
MrCode

Reputation: 64526

The issue is you are literally updating arrayIdx instead of the index that it refers to. You need to use a Computed Property Name like [arrayIdx].

[arrayIdx]: { content: { $set: con } }

Upvotes: 1

Related Questions