1

I am doing a simple quiz in my app with questions I'm putting in, I made 2 radio buttons as a trial, and then I made the on press function take the value of the pressed button, then test whether it's equal to the correct value, yet it's not working correctly, it sometimes alerts "good job" and sometimes "not correct" on both buttons. Here is the code :

import * as React from 'react';
import RadioForm from 'react-native-simple-radio-button';
import {
    Image, Platform, StyleSheet, Text, TouchableOpacity, View, radio, Alert, Button,
    ScrollView
} from 'react-native';

var radio_props = [
    { label: 'one', value: 1 },
    { label: 'two', value: 2 }
];

class Quiz extends React.Component {
    state = {
        value1: 0,
        correct1: 0,
    }

    checkquestion(value) {
        this.setState({ correct1: 1 })
        this.setState({ value1: value })
        if (this.state.value1 === this.state.correct1) {
            Alert.alert("goodk job")
        }
        else {
            Alert.alert("not correct")
        }

    }
    render() {
        return (
            <View>
                <Text>Choose number one</Text>
                <RadioForm
                    radio_props={radio_props}
                    onPress={(value) => { this.checkquestion(value) }}
                />
            </View>
        )
    }
}
export default Quiz

`

3
  • The code snippet is not working, it gives this error message Uncaught SyntaxError: Cannot use import statement outside a module Commented May 3, 2020 at 10:43
  • post here RadioForm component also Commented May 3, 2020 at 10:49
  • Not sure why it gives you an error, I'm not getting any Commented May 3, 2020 at 10:59

1 Answer 1

2

I think you're being caught out by the fact that setState works asynchronously... At the moment you are calling setState twice and then referencing state immediately afterwards. In this setup you don't know whether you are referencing the new or old state, which is why it 'sometimes' works; it's a race condition.

You should use the callback argument on setState. I've created a new method called displayAlert for you, which gets called once setState has completed. I also recommend setting both states simultaneously as I have done in this code. This should prevent any weirdness.

 displayAlert = () => {
    const {value1, correct1} = this.state;
    const isCorrect = value1 === correct1;
    const alertMessage = isCorrect ? "Good job!" : "Not correct";

    Alert.alert(alertMessage);
  };

  checkquestion = value => this.setState({correct1: 1, value1: value}, this.displayAlert);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.