Home > Software engineering >  Problem with updating state in react native component
Problem with updating state in react native component

Time:04-01

I have an array with values i want to present and then if the user press the edit button the presentation is changed to a list of TextInput components. When done editing the user can press Save or Cancel. If Cancel is pressed the values in the textInput fields should not be saved to the original array of values.

enter image description here

enter image description here

My problem is that even when pressing Cancel the data in the original array seems to be updated.

This is the code:

`

const handlePress = (text, index) => {
    const newSchedule = [...scheduleTempState]
    newSchedule[index].value = text
    setScheduleTempState(newSchedule)
  }


  const handlePress2 =()=>{
    setScheduleTempState([]); 
    console.log("handlepress2")
    setEdit(false)
   }  
  
   const handlePress3 =()=>{
    setScheduleTempState(scheduleState); 
    console.log("handlepress3")
    setEdit(true)
   }  
  

return (
    edit
    ?
    <View style={styles.scheduleRow}>
        <View style={styles.buttonView}>
            <TouchableOpacity onPress = { ()=>{saveSchedule(projectId,scheduleState);updateClient() ;setEdit(false)}} >  
                <MaterialIcons name="save" size={16} color="green" />
            </TouchableOpacity>
            <TouchableOpacity onPress = { ()=>{handlePress2()}} >  
                <MaterialIcons name="cancel" size={16} color="red" />
            </TouchableOpacity>
        </View>
       <View>
        <FlatList
            horizontal = {true}
            data={scheduleTempState}
            keyExtractor={item => item.id}
            renderItem={({item, index}) => {
            return (
                <View style={styles.decimalInputView}>
                    <TextInput 
                        style={styles.cellInput}    
                        onChangeText={(text) => {handlePress(text, index)}} 
                        value = {item.value} />
                </View>
                )
            }}
        />  
        </View>        
    
    </View>
    :
    <View style={styles.scheduleRow}>
        <View style={styles.buttonView}>
            <TouchableOpacity onPress = { ()=>handlePress3()} >  
                <MaterialIcons name="edit" size={14} color="black" />
            </TouchableOpacity>
        </View>
        <View >
           <FlatList
            horizontal={true}
            data={scheduleState}
            renderItem={renderScheduleItem}
            keyExtractor={item => item.id}
          />
        </View>
      
    </View>
);

}`

I guess my problem has something to do with states not being updated, but i can not see how the edited values can be saved when i press cancel.

CodePudding user response:

Problem: You are updating the scheduleTempState by referencing your scheduleState. So when you mutate scheduleTempState, it also mutates the scheduleState.

Solution: Please use spread operator for array destructuring which can help to create a new copy of a reference.

const handlePress3 =()=>{
    setScheduleTempState([...scheduleState]);
    ...
}

Suggestion: It would be better to use explanatory names for function. It will make the code more readable. For example:

  1. onChangeText() instead of handlepress()
  2. onCancelEditing() instead of handlepress2()
  3. onEdit instead of handlepress3()

Hope you will get the idea.

  • Related