Next.js Discord

Discord Forum

useState never seems to run in useEffect

Unanswered
Giant panda posted this in #help-forum
Open in Discord
Giant pandaOP
'use client'
import React, {useEffect, useRef, useState} from 'react';
import FlashCard from "@/app/components/FlashCard";
import {getRandomQuestion} from "../util/AudioService"
import AnswerTracker from "@/app/components/AnswerTracker";

function QuizCard({group}) {

    const [showNextQuestion, setNextQuestion] = useState(false);
    const [question, setQuestion] = useState();
    const correctRef = useRef(0);
    const wrongRef = useRef(0);

    function getNextQuestion() {
        let data = getRandomQuestion(group)
        setQuestion(data)
        console.log("init question")
        console.log(data)
        setNextQuestion(false)
    }

    useEffect(() => {
        let data = getRandomQuestion(group)
        console.log("init question")
        console.log(data)

        setQuestion(data)
        setNextQuestion(false)
    }, [])

    return (<div className="flex flex-col mx-auto">

        <FlashCard q={question} shouldFlip={showNextQuestion}
                   setShouldFlip={setNextQuestion} getNextQuestion={getNextQuestion} wrongRef={wrongRef}
                   correctRef={correctRef}></FlashCard>
        <AnswerTracker correctRef={correctRef} wrongRef={wrongRef}></AnswerTracker>

    </div>);
}

export default QuizCard;
I have the following code. However, in FlashCard, q is null and I am unsure why

6 Replies

Giant pandaOP
init question also never gets printed
Spectacled Caiman
Do you get any error messages or is it just that your use-effect never fires?
@Spectacled Caiman Do you get any error messages or is it just that your use-effect never fires?
Giant pandaOP
FlashCard uses q, since it is json data, it tries to access data inside and gets null
Spectacled Caiman
Try to re-create the issue. Create a new blank component and call that function in a useEffect. See if its works there. If not trying use some print statements to see if the component is being mounted or not.
However,
The issue could be because useState doesn't fire immdiatly and gets scheduled so you might be trying to pass the value to the component without it first getting set.