setfunction of react hook inside onPress not working !
Closed this issue · 1 comments
joy-mollick commented
`
const [gender,setgender] = useState('Male');
const radioButtonsData = [{
id: '0', // acts as primary key, should be unique and non-empty string
label: 'Male',
/// value: 'option1'
}, {
id: '1',
label: 'Female',
/// value: 'option2'
}, {
id: '2',
label: 'Gay',
/// value: 'option2'
}
, {
id: '3',
label: 'Straight',
}
]
const [radioButtons, setRadioButtons] = useState(radioButtonsData);
function onPressRadioButton(radioButtonsArray) {
setRadioButtons(radioButtonsArray);
console.log(radioButtonsArray);
for(let j=0;j<radioButtonsArray.length;j++)
{
if(radioButtonsArray[j].selected==true)
{
setgender(radioButtonsData[j].label)
console.log(j)
}
}
console.log(gender);
}
return (
<View style={{ flex: 1 }}>
<View style={{ width: '92%', alignSelf: 'center', padding: 10 }}>
<Text style={{ fontWeight: 'bold', fontSize: 18 }}>Sexual Orientation</Text>
<View style={{alignSelf:'center'}}>
<RadioGroup
radioButtons={radioButtons}
onPress={onPressRadioButton}
/>
</View>
</View>
</View>
)`
Can you plz tell ? why inside onpress , another state is not updating ? What is the usage of this library ?
ThakurBallary commented
console.log(gender)
will not wait for setgender
to complete. So, we should listen to the changes in gender value using useEffect
.