'How to change value of dummy data in React Native

I have dummy data for UI testing as belows

let sampleData = [
    {
        name : "Banana",
        isFurit : true,
        volume: 0,
    },
    {
        name : "book",
        isFurit : false,
        volume: 0,
    },
    {
        name : "melon",
        isFurit : true,
        volume: 0,
    },
]

I want to change 'isFruit' value when I press button. but it doesn't work. wanna make text toggle like Fruit <=> Things when I click Touchbleopacity

{sampleData.map((data, index) => {
const {name,isFruit,volume} = data
return (
<View key={index}>
 <View>
  <Text style={[s.mediumFont]}>{name}</Text>
 </View>
 <View>
  <TextInput selectTextOnFocus={true} autoCapitalize={'none'} 
   keyboardType={'numeric'} onChangeText={(text) => {volume = 
   text}} 
   value={volume ? volume.toString() : ''}/>
  <Text>{isFruit ? 'Fruit' : 'Things'}</Text>
  <TouchableOpacity onPress={(isFruit) => (!isFruit)}>
   <Image style={[s.icon24]} source=. 
    {require('../../static/img/food/convert.png')}/>
   <Text>{!isFruit ? 'Fruit' : 'Things'}</Text>
  </TouchableOpacity>
 </View>
 <View>
  <TouchableOpacity onPress={() => this.addSelectedCustom()}>
   <Image style={[s.icon24]} source 
    {require('../../static/img/food/cancel.png')}/>
  </TouchableOpacity>
 </View> 
</View>
)
})}


Solution 1:[1]

Here is a TypeScript solution for your problem. Difficult to give a solution that works with your code as it was not fully provided. I use generic HTMLElements since I'm not familiar with the components you are using.

Also, I would suggest using immutable.js for immutable data structures, when working with React. Please have a look at this page from the React Documentation.

I hope this helped.

const SomeComponent : React.FC = props => {
    const [sample, setSample] = useState([
    {
        name : "Banana",
        isFruit : true,
        volume: 0,
    },
    {
        name : "book",
        isFruit : false,
        volume: 0,
    },
    {
        name : "melon",
        isFruit : true,
        volume: 0,
    }])

    const toggleFruit = (isFruit : boolean, index : number) => {
        const newSample = [...sample]
        
        // a shallow copy occurs with the values of sample objects
        newSample[index] = {
            ...newSample[index]
        }

        // mutations occurring here
        newSample[index].isFruit = isFruit

        setSample(newSample) // trigger re-render
    } 
    
    return <div>
        {sample.map((obj, i) => 
            <button 
                onClick = { () => toggleFruit(!obj.isFruit, i)} 
            >{`${ obj.name } - ${ obj.isFruit }`}</button>
           
        )}
    </div>
}

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 Ramzi