Dannz
Dannz

Reputation: 495

Toggle checkbox doesn't update UI

The state itself toggles but the UI doesn't.

The object looks as follows:

data: [ {id: 0, key: 'Key1', checked: false }, ... }]

Am i missing something in my implementation?

 onCheckBoxChange(id) {
    let arr = Array.from(Object.create(this.state.data));
    arr[id].checked = !arr[id].checked;
    this.setState({
        data: arr
    })
 }

render() {
    return (
      <Container>
        <Content>
          <List dataArray={this.state.data}
            renderRow={(item) =>
                <View>
                    <ListItem>
                      <CheckBox checked={ this.state.data[item.id].checked }
                       onPress={()=> this.onCheckBoxChange(item.id)}/>
                <Text>{item.key}</Text>
              </ListItem>
            </View>
          }>
        </List>
      </Content>
    </Container>
    )   
  }
}

Upvotes: 0

Views: 103

Answers (1)

Matt Aft
Matt Aft

Reputation: 8936

I believe you're mutating the state, also you're using the id to determine the index. Try this out:

onCheckBoxChange(index) {
    const arr = [...this.state.data];
    const newItem = {
      ...arr[index],
      checked: !arr[index].checked,
    };
    arr[index] = newItem;

    this.setState({
        data: arr
    })
 }

render() {
    return (
      <Container>
        <Content>
          <List dataArray={this.state.data}
            renderRow={(item, index) => // use index instead of id
                <View>
                    <ListItem> // you already have the item so dont need to go check from state
                      <CheckBox checked={ item.checked }
                       onPress={()=> this.onCheckBoxChange(index)}/>
                <Text>{item.key}</Text>
              </ListItem>
            </View>
          }>
        </List>
      </Content>
    </Container>
    )   
  }
}

Upvotes: 1

Related Questions