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
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.
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.
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.