Home > Net >  Fetch API And Render Component more than one time in Next Js
Fetch API And Render Component more than one time in Next Js

Time:08-09

I Have Use Next Js

And I Don't Know Why Mine API is Calling 2 or More Time even i have set if data have been loaded then don't fetch data

And Also quiz.js Component is Rendering Twice, Here is Mine Code

File Name : question.js

Code

export default function Question() {
    const [quiz, setQuiz] = useState("");
    const [ loading , setLoading ] = useState(true);

    useEffect(() => {

        const fetchData = async () => {

            if(loading) {
                  const response = await fetch("/api/quiz");
                  const data = await response.json();

                 setQuiz(data.message);
                 setLoading(false);

           } else {
                 setLoading(false);
     }

   }

   fetchData();
}, []);


 if (loading) {
     return <> </>;
 }

return (
<>
  <Head>
    <title>{`Quiz - Play And Win with Quizy`}</title>
    <meta name="description" content="Login Page" />
    <link rel="icon" href="/favicon.ico" />
  </Head>

  <section className="mobile start">
    {/* <span> {quiz} </span> */}
    {
      !loading ? <Quiz totalQuiz={2} quizy={quiz} /> : <></>
     }
  </section>
</>
);
}

File Name : quiz.js

Code :

export default function Quiz({ totalQuiz, quizy }) {
     // set First Quiz
     const [quiz_no, setQuizNo] = useState(1); // current quiz no
     const router = useRouter();


     console.log("Line 12 : File Name : ./components/quiz.js");
     console.log(quizy);

     if (typeof window !== 'undefined') {
        console.log("For Client Side Only");
     }

     const handleClick = (ans) => (e) => {
         e.preventDefault();

         if(quizy[0][quiz_no - 1].quizAnswer == ans) {
               e.currentTarget.classList.add('true');

              setTimeout(() => {
    
                 if (quiz_no < totalQuiz) {
                      e.currentTarget.classList.remove('true');

                      setQuizNo(quiz_no   1);
                } else {
                      router.push("/start");
                }
        }, 1000);
   } else {
        e.currentTarget.classList.add('false');

  setTimeout(() => {
      e.currentTarget.classList.remove('false');
      if (quiz_no < totalQuiz) {
         setQuizNo(quiz_no   1);
      } else {
         router.push("/start");
      }
    }, 1000);
  }
}

Code Output And Console Logs

CodePudding user response:

I'm kinda guessing here but maybe something is triggering a route change. or if you use a global state management (i.e. redux), you are triggering something that causes the Question component to remount (because thats the only things that can cause the refetching).

either:

  1. you fetch the quiz data in getServerSideProps (so before you do all the client side stuff)
  2. you stop the stuff that causes the remounting. something to do with the parent components of Question.

You can use a react debugger tool to find components that also remounts. If the parent component remounts then the problem is somewhere else in the code.

I'm sorry if this doesn't truly answer your question but I hope this helps.

CodePudding user response:

It might be because of Strict Mode, which would not affect your production build, but you can turn it off in your next.config.js file.

Strict mode helps you find unexpected side-effects by intentionally calling some methods twice (such as function component bodies).

  • Related