ThakurBallary / react-native-radio-buttons-group

Simple, best and easy to use radio buttons for react native apps.
MIT License
248 stars 70 forks source link

setfunction of react hook inside onPress not working ! #36

Closed joy-mollick closed 2 years ago

joy-mollick commented 2 years ago

` 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 2 years ago

console.log(gender) will not wait for setgender to complete. So, we should listen to the changes in gender value using useEffect.

Here is the working example on expo snack