Toggle switch is not working properly in react native flat list

Viewed 386

I have a flat list that renders using the data from the redux state. Data is an array of objects in which I have a boolean value based on that I'm rendering a toggle switch.

The data from the redux is huge and currently does not have any pagination enabled. The problem is while I'm trying to update the switch value it's going to a false state and returns to true immediately and vice versa.

I can't update the redux state each time for switch values as the data is huge and will take time to re-render. Is there any way to keep the switch enable/disable without actually depending on the redux data.

code:

<FlatList
  data={this.props.data}
  renderItem={this.renderlist}
  keyExtractor={item => item.id}
  maxToRenderPerBatch={10}
  initialNumToRender={5}
  updateCellsBatchingPeriod={1}
  windowSize={7}
/>

Render function

const renderlist = ({ item }) => {
  return (
    <TouchableOpacity>
      <Text>{item.name}</Text>
      <Switch
        value={item.status ? true : false}
        onValueChange={(val) => {
          this.editData(item, val);
        }}
        color={COLORS.primary}
        style={styles.switch}
      />
    </TouchableOpacity>
  )
}

1 Answers

Even though you may be using redux, you still have component state available to you. If the toggle is something local to a particular component, why not consider using the traditional this.state? If you need it across the entire app, a dispatch on componentWillUnmount() should suffice when you go to the next component.

Related