I am trying to alert the user when they press submit as to what option they chose based on the CheckBox
.
The problem I am having is that when I check the checkbox of today
and tomorrow
the actual state outside the handleSubmit function is true however in the handleSubmit
function both today
and tomorrow
are false and I don't know how to get the actual state to render in useCallBack
hook.
Please can someone see where I am going wrong and assist me. Thank You!!!
import React, { useEffect, useState, useCallback } from 'react'
import { CheckBox } from 'react-native-elements'
import { Alert } from 'react-native'
const Choose = (props) => {
const [today, setToday] = useState(false)
const [tommorow, setTommorow] = useState(false)
useEffect(() => {
props.navigation.setParams({ handleSubmit: handleSubmit })
}, [handleSubmit])
console.log(`today is ${today}`) // this works and is changed by the check box
const handleSubmit = useCallback(() => {
if (today == true){
console.log(`today is ${today}`) // today from outise this function is never true
Alert.alert('You selected today')
}else if (tommorow == true){
Alert.alert('You selected tommorow')
}
}, [today, tommorow])
return (
<View>
<CheckBox
checked={world}
onPress={() => setToday(!today)}
title='Today'
/>
<CheckBox
onPress={() => setTommorow(!tommorow)}
title='Tommorow'
/>
</View>
)
}
export default ChooseToAdd
Choose.navigationOptions = () => {
const submit = navigationData.navigation.getParam('handleSubmit')
return {
headerRight: () =>
<TouchableOpacity onPress={submit}>
<Text>Submit</Text>
</TouchableOpacity>
}
}
your useEffect which trigger on handleSubmit is defined before the definition of handleSubmit
You have to write useEffect hook after handleSubmit function
use toggleHandler function for both today & tomorrow
setState(prev => !prev)
Use if statement for both case because you have checkbox not radio button, So there is chances of both check boxes is checked.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.