'how to increase or decrease the count based on array index

I need increase or decrease the product count based on the array index. while using this function data value is updating but flatlist not get rendering the updated value

import  React ,{useState} from 'react';
import { Text, View, StyleSheet,FlatList,Button } from 'react-native';

const addCount = () => {
  const [data,setData] = useState([{
    id : 1,
  name : "Mongo",
  price : 30,
  qty : 1
},
{
  id : 2,
  name : "lemon",
  price : 30,
  qty : 1
}])
const addQty = (ind) => {
setData(data[ind].qty + 1)
}
  return (
    <View>
  <FlatList
        data={data}
        renderItem= {({item,index})=>{
          return (
            <View>
            <Text>name: {item.name}</Text>
            <Text>qty : {item.qty}</Text>
            <Text>price : {item.price}</Text>
            <Button  title = "add Qty" onPress = {()=>{
              addQty(index)
            }}/>
            </View>
          )
        }}
        keyExtractor={item => item.id}
      />
    </View>
  )
}

export default addCount

Thanks!!



Solution 1:[1]

You should not directly mutate the array instead you have to provide a new array in order to update the state so try:

setData(data.map((obj,index)=> index == ind ? { ...obj, qty:obj.qty+1} : obj ))

Solution 2:[2]

Just update the code as below, and make it so simple, as we are iterating over the json object, we don't want to use the spread operator,

setData(data.map((obj, index) => index == ind ? obj.qty++ : obj))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 praveen jkp