1
   function handlePairButtonsPressed(e) {
        console.log(e.target.getInnerHTML());
        setAnswerValue(e.target.getInnerHTML());
        console.log(answerValue);
        handleSubmitButton();
   }

   function handleSubmitButtonPressed() {
        let fd = new FormData();
        let csrftoken = getCookie('csrftoken');
        questionID = roomData.round_list[displayedTable][3]
        experimentID = roomData.round_list[displayedTable][4]
        pair_or_question = roomData.round_list[displayedTable][5]
        console.log(answerValue);
        fd.append('answerValue', answerValue);
        fd.append('experimentID', experimentID);
        fd.append('questionID',  questionID);
        fd.append('pair_or_question', pair_or_question);

        fetch('/audio/answerQuestion_POST/', {
            method: 'POST',
            headers: { "X-CSRFToken": csrftoken },
            body: fd
        });
   }

So I have two buttons called "pair buttons" which set the answerValue and automatically submit. Otherwise a user may type their own answerValue and submit that. The functions these buttons call are shown above. AnswerValue is a state variable btw.

The two console.logs() in handlePairButtonsPressed() print what I want. The second one confirms that the state variable AnswerValue has been set to the right value by setAnswerValue(). And yet, when handleSubmitButtonPressed() is called right afterwards, it recognises the old answerValue and not the new one. If I press the submit button afterwards to trigger just handleSubmitButtonPressed() again, THEN it uses the new answerValue set by handlePairButtonsPressed(). I'm not sure how to fix this.

Any help would be appreciated. Thanks.

a b
  • 41
  • 2
  • You can't use a newly set state value in the same render cycle, as it won't be updated until the next. – pilchard Feb 28 '22 at 18:07
  • Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – pilchard Feb 28 '22 at 18:08

0 Answers0