skip to Main Content

I’m building a project with vite + react app.
I fetched data in useEffect() and got the following error in console:
GET https://opentdb.com/api.php?amount=5&category=9&difficulty=medium&type=multiple 429 (Too Many Requests)

Here’s my code :

import React,{useState,useEffect} from 'react'

function QuizMain() {
    const[data,setData] = useState()
    useEffect(()=> {
        fetch("https://opentdb.com/api.php?amount=5&category=9&difficulty=medium&type=multiple")
        .then((res)=> res.json())
        .then((data)=>console.log(data))
    },[])
  return (
    <div >...</div>
  )
}

I set the second argument in useEffect(function,[]), why is it fetching multiple times? How to I fix it? I’m a newbie!

I am expecting to fetch data only one time on render and update the state.

2

Answers


  1. Firstly, React will render your components twice in development mode, see this article for more on that https://react.dev/reference/react/StrictMode

    Second, you’re not actually setting the state to the fetched data.

    import React,{useState,useEffect} from 'react'
    
    function QuizMain() {
        const[data,setData] = useState()
        useEffect(()=> {
          (async () => {
            const response = await fetch("https://opentdb.com/api.php?amount=5&category=9&difficulty=medium&type=multiple");
            // Check status codes and whatnot here and handle accordingly
            const data = await response.json();
            console.log(data);
            setData(data);
          })();
        },[])
      return (
        <div >...</div>
      )
    }
    

    If you’re still seeing multiple renders/fetches you’ll have to look in the parent components to see if something might be triggering new renders.

    Login or Signup to reply.
  2. Let’s test our API first. Open your API URL separately in a browser tab and check whether the JSON response is returned. Refresh the API multiple times and see the results are consistent. If not, the API is having some issue responding to request back to back or designed in a way to return the response after a configured wait time.

    In order to prevent react app from rendering its components twice is to take out the StrictMode from your root component. The code is just fine.

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search