'Too many re-renders while setting a state
Getting an error of Unhandled Runtime Error while setting a state in an axios get call. Even tested with a button click and confirmed that function is not called more that once. I don't know what is the problem with it.
Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
const [quizzesTaken, setQuizzesTaken] = useState([])
const quizzesTakenByUser = async () => {
try {
const res = await axios.get('/api/quizzes/quizzestaken')
setQuizzesTaken(res.data) // Getting error on this line.
} catch (error) {
log(error)
}
}
<button onClick={() => quizzesTakenByUser()}>Get Quizzes</button>
useEffect(() => {
if (gradeText !== 'none') {
getGradeDescription()
}
}, [gradeText])
This is how I render the components base on quizzesTaken
{quizzesTaken.map(q => {
return (
<QuizTakenItem
subject={
q.subject +
' ' +
q.class_name
}
correct={q.correct_ans}
total={q.total_questions}
/>
)
})}
Solution 1:[1]
The problem is solved after I removed the code setting the independent state of the child component but now it is a more annoying problem to the brain, why it was like that is still a question?
const [width, setWidth] = useState("10%")
const {correct, total} = props;
setWidth(((correct/total) * 100) + "%")
And thank you all for your help.
Solution 2:[2]
Did you try this way, using then() :
const [quizzesTaken, setQuizzesTaken] = useState([])
const quizzesTakenByUser = () => {
axios.get('/api/quizzes/quizzestaken')
.then(res => setQuizzesTaken(res.data)
.catch(error => console.log(error)
}
<button onClick={() => quizzesTakenByUser()}>Get Quizzes</button>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Maseed |
| Solution 2 | Aurélien |
