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}
/>
)
})}
CodePudding user response:
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.
CodePudding user response:
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>
CodePudding user response:
Did you tried like this?
<button onClick={quizzesTakenByUser}>Get Quizzes</button>