I have a TextInput field that when a user is editing, they have the option to cancel. The goal is to revert the TextInput value back to the original value before the user started editing, however, even though the previous value is stored and the screen is re-rendering, the text on the screen stays however the user left it. I'm assuming I'm just misunderstanding how the TextInput component works.
This is the input in question:
<TextInput
style={styles.workoutheader}
editable={editableWorkout == workout.id}
onChangeText={(workoutName) => setWorkoutName(workoutName)}
>
{workout.name}
</TextInput>
and this is the cancel button:
<TouchableOpacity
style={styles.workoutheadericon}
onPress={() => {
console.log('Reverting to: ' prevWorkoutName, prevWorkoutType, prevWorkoutWeight, prevWorkoutReps);
setWorkoutName(prevWorkoutName);
setWorkoutType(prevWorkoutType);
setWorkoutWeight(prevWorkoutWeight);
setWorkoutReps(prevWorkoutReps);
setEditableWorkout('');
setIsEditing(!isEditing);
setActionCounter(actionCounter 1);
}}
>
{workout.name}
is coming from a firestore database, but I don't think that's related.
CodePudding user response:
I don't think the variable workout
gets updated when you call setWorkoutName
, try replacing {workout.name}
with workoutName
or whatever variable name you used where you declared your useState
function that created the setWorkoutName
setter function, e.g.
const [workoutName, setWorkoutName] = useState(workout.name)
return (
<TextInput
style={styles.workoutheader}
editable={editableWorkout == workout.id}
onChangeText={(workoutName) => setWorkoutName(workoutName)}
>
{/* should be `workoutName` here, not `workout.name` */ workoutName}
</TextInput>
)
CodePudding user response:
SOLUTION
I needed to target the workout being edited with
editableWorkout == workout.id ? workoutName : workout.name}
which let me differentiate between the workouts using Leon Si's answer.