Reputation: 572
I have a component with two states name
and email
whose initial values are coming from previous route ,
the state does change on using setter methods but , when i try to access the state values in from handler it always gives the default values
Here is the code
const EditProfileScreen = (props) => {
const [name, setName] = useState(props.navigation.getParam('name'))
const [email, setEmail] = useState(props.navigation.getParam('email'))
const nameHandler = (text) => {
setName(text)
}
const emailHandler = text => {
setEmail(text)
}
const handleSubmit =() => {
console.log(name)
// It returns the default value not the updated one
}
return (
<View>
<TextInput style={styles.input} onChangeText={emailHandler} value={email} />
<TextInput style={styles.input} onChangeText={nameHandler} value={name} />
</View>
)}
Any help will be appreciated
Upvotes: 1
Views: 72
Reputation: 1065
I'm not sure why this is happening, but as a workaround you can introduce the useEffect
hook:
const [name, setName] = useState('')
const [email, setEmail] = useState('')
useEffect(() => {
setName(props.navigation.getParam('name'))
setEmail(props.navigation.getParam('email'))
}, []);
Upvotes: 1