Okay so I hope this is easy, but I can't find anything about that on Google.
I have a details screen for a (cooking)receipe in my app. With the tap of a button the user can set a state isEditing
, which then converts a heading into a text input. That heading displays {receipe.title}
and I use the same value for the default value
prop on the text input.
Once the user taps the edit button again, isEditing
will be set to false and a update function will update the receipe in my Firebase database.
{!isEditing ? (
<Text style={styles.headingLarge}>{receipes.title}</Text>
):(
<TextInput
placeholder='Titel'
autoFocus={true}
defaultValue={receipes.title}
style={styles.headingLarge}
onChangeText={text => {
setPresentTitle(text);
}}/>
)}
It's all working, as long as the user actually changes something in the input. But the issue is that if a user doesn't change anything, onChangeText
is never called and the database is updated with an empty string as it's title.
Is there a way to call the onChangeText
when setting the defaultValue for this input (or another hack to set the setPresentTitle
)?
CodePudding user response:
Hey you can check this snack out, ive made it for you
This is the snack : https://snack.expo.dev/@gaurav1995/fascinated-donut
Hope it helps. feel free for doubts
import React,{ useState ,useEffect } from 'react';
import { StyleSheet, Text, TouchableOpacity, View ,TextInput ,Button } from 'react-native';
export default function App() {
const receipes = {
title:"Hey there"
}
const [isEditing, setEd] = useState(false)
const [text,setPresentTitle] = useState(receipes.title)
const toggleEdit = () => {
setEd(!isEditing)
}
useEffect(() => {
//update to firebase
//setFirebase(text)
},[text])
return (
<View>
{!isEditing ? (
<Text style={styles.headingLarge}>{text}</Text>
):(
<TextInput
placeholder='Titel'
autoFocus={true}
value={text}
style={styles.headingLarge}
onChangeText={text => {
setPresentTitle(text);
}}/>
)}
<Button title="Toggle Edit" onPress={toggleEdit} containerStyle={{marginTop:20}} />
</View>
)
}
const styles = StyleSheet.create({
container:{
flex:1,
padding:40
},
headingLarge:{
fontSize:40,
marginBottom:20
}
})