1

I have a FlatList and I want to show a number like quantity of product. So I use a state for that. Now when I press on TouchableOpacity to change quantity to 1 working fine in console, but I can't see any change in FlatList.

  constructor(props){
    super(props);
    this.state={
      quantity : 0,
    }

Increment quantity:

incrementCount=()=>{

    if(this.state.quantity != 10){
      console.log(this.state.quantity);
     this.setState((prevState, props) => ({
        quantity: this.state.quantity + 1,
      }));
    }
}

FlatList:

<FlatList
          data={this.state.dataSource}
          renderItem={({item}) =>

          <View>
            <Text>{item.title}</Text>

            <Text>{this.state.quantity}</Text>                            
            <TouchableOpacity onPress={this.incrementCount} activeOpacity={0.5}>
               <AntDesign name="plus" size={15}/>
            </TouchableOpacity>

          </View>
      }
    />

2 Answers2

0

Listview is deprecated now use Flatlist instead of this.

Refer this official doc for more information react-native listview

Ankit Dubey
  • 243
  • 3
  • 11
0

This is the common problem about pre-increment vs post-increment in javascript (you can read more about this here: ++someVariable Vs. someVariable++ in Javascript )

You can solve this problem by simply incrementing the variable before the setState:

const quantity = this.state.quantity + 1;
this.setState({ quantity }) // this is ES6 syntax

Anyway, you should not use ListView because it's deprecated. ( https://facebook.github.io/react-native/docs/listview.html ) There are other components:

vitosorriso
  • 765
  • 1
  • 7
  • 16