-1

I currently am using data stored in Firebase to check if a user-submitted solution is correct. This involves me calling the function getSolutionAndCompare when the user presses a “submit” button. However, for some reason, although checkSolution is returning true to getSolutionAndCompare, when I call getSolutionAndCompare in onSubmitPressed, it evaluates as undefined. Any idea what I could be doing wrong?

Relevant code:

onSubmitPressed: function() {
    var output = this.getSolutionAndCompare();
    console.log('output ' + output); //this is returning undefined
    if (this.getSolutionAndCompare()) {
        Alert.alert(
            'Correct',
            "Woohoo!"
        );
    }
    else {
        Alert.alert(
            'Incorrect Submission',
            'Try again!',
        );
    }
},

getSolutionAndCompare: function() {
    var databaseSolution;
    solutionsRef.orderByChild('question_id').equalTo(Number(this.props.questionId)).once('value', (snap) => {
        var solution = snap.val();
        for (var key in solution) {
            databaseSolution = solution[key].solution;
        }
        return this.checkSolution(databaseSolution); //checkSolution returns true here
    });

},

checkSolution: function(databaseSolution) {
    if (this.state.submission == databaseSolution) {
        return true;
    }
    else {
        return false;
    }
},
user3802348
  • 2,502
  • 11
  • 36
  • 49
  • What kind of data are you expecting to be in held in `solution` here? `var solution = snap.val()`? You go on to iterate over the `solution` object but you're only checking the final value in your return statement. Edit - that return statement doesn't appear to be returning the `getSolutionAndCompare` method so that method returns `undefined` – bcr May 23 '16 at 14:57
  • `solutionsRef.orderByChild('question_id').equalTo(Number(this.props.questionId)).once('value', (snap) => {` -- is this an async call? Either way, you are returning inside of an inner function, which isn't what you want. – Jeremy J Starcher May 23 '16 at 14:58

1 Answers1

3

getSolutionAndCompare doesn't have a return statement, so it returns undefined because that is the default.

(The anonymous arrow function you declare inside getSolutionAndCompare has a return statement, but that looks asyncronous so you can't return its value).

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335